0

I have a txt File that is similar to the following

example.txt

9987.000 2300 23 40 30 
9654.988 1234 34 32 19

I would like to iterate over this file and rewrite it into another file sample.txt as follows each number on its own line listed vertically in order in which they are listed horizontally.

9987.000
2300
23
40
30

I am new to Python and am not sure which would be the best approach for doing something like this. Any advice is greatly appreciated. Syntax Error

     File "Sample.py", line 64 
       with open('testFile.txt')as infile, open('testFile.txt','w') as outfile:
                                         ^
     SyntaxError: invalid syntax  
  • Are you sure that's the error? Try adding a space between `open(...)` and `as`. [This syntax should really work on Python2.7](http://stackoverflow.com/a/4617069/198633) – inspectorG4dget Jul 31 '13 at 18:38
  • Thanks I was able to get it to work had an error further up in the code was not in this function. – user2612524 Aug 02 '13 at 16:23

1 Answers1

0

For large files:

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        for num in line.strip().split():
            outfile.write(num + '\n')

For small files:

import itertools
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    outfile.write('\n'.join(itertools.chain.from_iterable(line.strip().split() for line in infile)))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • So when I try to replicate this exactly as you have it. I get a syntax error as follows with open('sample.txt') as infile, open('sample.txt','w') as outfile: ^ Seems the error is with the comma or do I need to import something? I took the comma out but it still didnt work Can you help me figure out what I am doing wrong. Thanks – user2612524 Jul 26 '13 at 00:28
  • @user2612524: That doesn't tell me anything about your error. Also, you should edit the error into your original post, rather than include in a comment – inspectorG4dget Jul 29 '13 at 23:59
  • ok Sorry now it should be easier to read Thanks for all your help also my numbers will be read in as strings and I will need to convert them to numbers do I just cast them as follows (float) – user2612524 Jul 31 '13 at 17:59