Reputation: 853
Here is my code:
import fileinput
input_file = 'in.txt'
output = open('out.txt', 'w+')
for each_line in fileinput.input(input_file):
output.write(x.strip() for x in each_line.split(','))
I get "expect character buffer" as the error. I am not sure what is the best way to go about this? I am trying to remove all tabs and spaces and replace them with a comma.
edit: forexample my data looks like:
1 2335 mike
1 4089 doug
and I want to turn it into
1,2335,mike noll
1,4089,doug funny
edit, i only want to remove the first 2 spaces in the first 2 columns
Upvotes: 0
Views: 6556
Reputation: 250931
Use str.join
to join the list into a string and then write it to the file.
In your code you're actually passing a genexp to file.write
.
for each_line in fileinput.input(input_file):
output.write(" ".join(x.strip() for x in each_line.split(',')) +'\n')
Update:
with open('out.txt', 'w') as f:
for line in fileinput.input('input.txt'):
line = line.split(None,2)
f.write(','.join(line))
Upvotes: 0
Reputation: 99620
x.strip() for x in each_line.split(',')
does returns a generator object (not a string buffer that is expected by the output.write
)
You can do:
with open('out.txt', 'w+') as output:
for each_line in fileinput.input(input_file):
output.write("\n".join(x.strip() for x in each_line.split(',')))
Upvotes: 1