George Grigorita
George Grigorita

Reputation: 1890

Python: read file - modify line - write output

I have a list of terms in a file that I want to read, modify each term and output the new terms to a new file. The new terms should look like this: take the first two characters of the original term put them in quotes, add a '=>' then the original term in quotes and a comma.

This is the code I'm using:

def newFile(newItem):
    original = line
    first = line[0:2]
    newItem = first+'=>'+original+',' 
    return newItem
input = open('/Users/george/Desktop/input.txt', 'r')
output = open('/Users/george/Desktop/output.txt', 'w')
collector = ''
for line in input: 
   if len(line) != 0:
       collector = newFile(input)
       output.write(''.join(collector))
   if len(line) == 0:
       input.close()
output.close() 

For example: If the terms in the input.txt file are these: term 1 term 2 term 3 term 4

The output is this:

te=>term 1
,te=>term 2
,te=>term 3
,te=>term 4    
,

How can I add '' to the first two letters and to the term? And why the second, third and forth terms have ,te not te like it should?

Upvotes: 0

Views: 2822

Answers (1)

Michał Niklas
Michał Niklas

Reputation: 54312

Instead of using collector and newFile() you can use new variable:

modified_line = "'%s'=>'%s',"  % (line[:2], line.strip())

and in your loop try this:

...
if len(line) > 2:
    output.write('%s\n' % (modified_line))

Also:

  • if possible do not hard code file names in your program, use sys.argv, standard input/output or config file; of course if you are sure of input/output names then use them
  • in line[0:2] you can ommit 0 and use line[:2]
  • you should use try: - open file - read file etc. finally: close file
  • you don't need to check if len(line) == 0, for loop do it already and you will receive line with CRLF for empty lines, but end of input file is when for loop ends

Upvotes: 3

Related Questions