I have the following problem:
I have a folder with files. I want to write into those files their respective file path + filename (home/text.txt) .
How can I achieve this in python?
Thanks in advance for your time and help!
with open('FOLDER_NAME/FILE_NAME','w+') as f: Assuming the python file is in the same path as the folder.
You can use: .. to move back a directory.
file = open("path", "w+")
file.write("string you want to write in there")
file.close
With w+
it is for reading and writing to a file, existing data will be overwritten.
Of course, as Landon said, you can simply do this by using with
, which will close the file for you after you are done writing to it:
with open("path") as file:
file.write("same string here")
This second snippet only takes up 2 lines, and it is the common way of opening a file.
However if you want append to instead of overwriting a file, use a+
this will open and allow you to read and append. Which means existing data will still be there, whatever you write will be added to the end. The file will also be created if it doesn’t exist.
Read more: