Reputation: 1890
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
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:
sys.argv
, standard input/output or config file; of course if you are sure of input/output names then use themline[0:2]
you can ommit 0 and use line[:2]
try:
- open file - read file etc. finally:
close filelen(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 endsUpvotes: 3