0

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

1
  • 2
    x.strip() for x in each_line.split(',') evaluates to a generator (which you can turn into a list by surrounding with []s) but write() does not accept a generator. Commented Jun 28, 2013 at 20:17

2 Answers 2

1

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(',')))
Sign up to request clarification or add additional context in comments.

1 Comment

It returns generator object indeed
0

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))

2 Comments

How would I save it into a file? instead of printing it?
open a file x = open('filename','w') then just add a x.write(...) around what is after the print

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.