简体   繁体   中英

Python script not writing to txt file

I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. Specifically, "TextFile.txt" is not being updated and/or saved.

    openfile = open('/PATH/TextFile.txt','w')
    for line in lines:
        if line.startswith(start):
            openfile.write(keep+'\n')
            print ("test 1")
        else:
            openfile.write(line)
            print ("test 2")
    openfile.close()

I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc

It may be due to a permissions problem. I am running the script from the terminal by using:

   usr/bin/python PATH/script.py

Python is owned by "root" and script.py is owned by "Michael".

Since your code is running, there should be a file somewhere.

You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. Is the slash before PATH a mistake? Have you checked the path in your program is really where you are looking for the output file?

My first guess:

Does the file exist? If it does not exist then you cannot write to it. Try this to create the file if it does not exist: file = open('myfile.dat', 'w+')

Additionally manually opening and closing file handles is bad practice in python. The with statement handles the opening and closing of the resource automatically for you:

with open("myfile.dat", "w+") as f:
    #doyourcalculations with the file object here
    for line in f:
        print line

All, thank you for your input. I was able to figure out that it was writing to the new file, but it was overwriting with the same text. The reason was because ".startswith" was returning false when I expected true. The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM