0

I have tried a simple write .txt file in a python script using Raspberry Pi B+ but is not working. It does not show any error but I can see the file. The code is:

file = open('log.txt','r')
file.write('hi'+'\n')
file.close()

I have tried with 'w+' , 'a' , 'w'; and reboot.

python Desktop/BQ/log.py

And when opening the file it shows the error that does not exist in the directory:

cat Desktop/BQ/log.txt

Thanks for any help.

4
  • First off, if you want to write to a file, you need to open in a mode that allows writing: 'r' is for reading only. You probably want 'w' or possibly 'a'. Commented Mar 15, 2019 at 23:15
  • Secondly: I may be misunderstanding something, but where is this Desktop folder? Is it on the Raspberry Pi or on your local machine? If it's on the Pi, then are you running cat on that same machine? If you're running all these things on your desktop machine, then what does this question have to do with Raspberry Pi? Commented Mar 15, 2019 at 23:17
  • 1
    Finally: if you're providing the file name as just 'log.txt', then that file name is interpreted as being relative to the current working directory, not relative to the location of the .py file. So if you're launching the program as python Desktop/BQ/log.py and it writes to log.txt, the file won't be at Desktop/BQ/log.txt, it will be at log.txt (presumably ~/log.txt if Desktop is inside your home directory). Commented Mar 15, 2019 at 23:20
  • 1
    The file will be created in the current directory, which is not necessarily the same directory as the python script. Commented Mar 15, 2019 at 23:38

2 Answers 2

1
file = open('log.txt','r')
file.write('hi'+'\n')
file.close()

Won't work, because

file = open('log.txt','r')

opens the file in read mode. That's what the 'r' stands for. 'w' is for writing (which overrides the current file content. 'a' appends to the current file content (if you want to write a log, for example)

So if 'w' didn't work, make sure that the program is executed with sufficient permissions to write to that directory.

Sign up to request clarification or add additional context in comments.

Comments

0

"If you're launching the program as python Desktop/BQ/log.py and it writes to log.txt, the file won't be at Desktop/BQ/log.txt, it will be at log.txt (presumably ~/log.txt if Desktop is inside your home directory)".

Thanks, the file is created where the python file is called on the terminal. In my case, it wasn't my file's directory. The file was created somewhere else. It was a such an easy thing but I couldn't figure it out.

Thanks to @Daniel Pryden and @Jonh Gordon

Comments

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.