Jorge González
Jorge González

Reputation: 47

Python code not writing to file unless run in interpreter

I have written a few lines of code in Python to see if I can make it read a text file, make a list out of it where the lines are lists themselves, and then turn everything back into a string and write it as output on a different file. This may sound silly, but the idea is to shuffle the items once they are listed, and I need to make sure I can do the reading and writing correctly first. This is the code:

import csv,StringIO

datalist = open('tmp/lista.txt', 'r')

leyendo = datalist.read()
separando = csv.reader(StringIO.StringIO(leyendo), delimiter = '\t')

macrolist = list(separando)

almosthere = ('\t'.join(i) for i in macrolist)

justonemore = list(almosthere)

arewedoneyet = '\n'.join(justonemore)

with open('tmp/randolista.txt', 'w') as newdoc:
    newdoc.write(arewedoneyet)

newdoc.close()
datalist.close()

This seems to work just fine when I run it line by line on the interpreter, but when I save it as a separate Python script and run it (myscript.py) nothing happens. The output file is not even created. After having a look at similar issues raised here, I have introduced the 'with' parameter (before I opened the output file through output = open()), I have tried flushing as well as closing the file... Nothing seems to work. The standalone script does not seem to do much, but the code can't be too wrong if it works on the interpreter, right?

Thanks in advance!

P.S.: I'm new to Python and fairly new to programming, so I apologise if this is due to a shallow understanding of a basic issue.

Upvotes: 0

Views: 228

Answers (2)

Francisco Puga
Francisco Puga

Reputation: 25159

Where are the input file and where do you want to save the output file. For this kind of scripts i think that it's better use absolute paths

Use:

open('/tmp/lista.txt', 'r')

instead of:

open('tmp/lista.txt', 'r')

I think that the error can be related to this

Upvotes: 4

Anthony Kong
Anthony Kong

Reputation: 40654

It may have something to do with where you start your interpreter.

Try use a absolute path /tmp/randolista.txt instead of relative path tmp/randolista.txt to isolate the problem.

Upvotes: 2

Related Questions