I am currently stuck with the following error:
IOError: [Errno 2] No such file or directory: '/home/pi/V1.9/Storage/Logs/Date_2018-08-02_12:51.txt'
My code to open the file is the following:
nameDir = os.path.join('/home/pi/V1.9/Storage/Logs', "Date_" + now.strftime("%Y-%m-%d_%H:%M") + ".txt")
f = open(nameDir, 'a')
I am trying to save a file to a certain path, which is /home/pi/V1.9/Storage/Logs. I am not sure why it can't find it, since I have already created the folder Logs in that space. The only thing being created is the text file. I am not sure if its suppose to join up like that, but I generally tried to follow the stages on this thread: Telling Python to save a .txt file to a certain directory on Windows and Mac
The problem seems to be here:
f = open(nameDir, 'a')
'a' stands for append, which means: the file should already exist, you get an error message because it doesn't. Use 'w' (write) instead, Python will create the file in that case.
If you are creating the file use the write mode w or use a+
f = open(nameDir, 'w')
f = open(nameDir, 'a+')
Use only a append if the file already exist.
Not really an answer to your question, but similar error. I had:
with open("/Users//jacobivanov/Desktop/NITL/Data Analysis/Completed Regressions/{0} Temperature Regression Parameters.txt".format(data_filename), mode = 'w+') as output:
Because data_filename was in reality a global file path, it concatenated and looked for a non-existent directory. If you are getting this error and are referring to the file path of an external file in the name of the generated file, check to verify it isn't doing this.
Might help someone.
Related
I was having issues writing to file, I've tried a lot of different methods of writing to file and none have worked. I was trying to figure out what was causing it so have used f.open, write, close to narrow down where the issue is coming from. I've narrowed it down to the pd.read_excel file here:
import glob
import os
# Open most recent file (probably to be changed)
list_of_files = glob.glob(r'C:\Users\gamo0\Downloads\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
f = open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
df = pd.read_excel(latest_file,sheet_name = 'People in your team',header=8)
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
It successfully writes to demofile1.txt and closes it. But then fails on writing to demofile2.txt with the following error:
f = open("demofile2.txt", "a")
FileNotFoundError: [Errno 2] No such file or directory: 'demofile2.txt'
A lot of similar issues talk about using absolute paths rather than relative, but it doesnt appear to be an issue with that as it can write to demofile1.txt fine.
N.B. if I move both write to demofiles above the pd.read_excel line, it will successfully write to both.
Any help would be appreciated.
I think it may be to do with how you are trying to write to the file. Try changing your open and write lines from:
f = open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
to
with open("demofile1.txt", "a") as f:
f.write("Now the file has more content!")
Using context managers is good practice when working with files. From the documentation here:
Context managers allow you to allocate and release resources precisely when you want to.
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:
https://www.geeksforgeeks.org/reading-writing-text-files-python/
Correct way to write line to file?
I m using the command testFile = open("test.txt") to open a simple text file and received the following: Does such errors occur due to the version of python one uses?
IOError: [Errno 2] No such file or directory: 'Test.txt
add an "a+" mode argument on to your open, this will create the file if it doesn't exist:
testFile = open("test.txt", "a+")
Syntax for opening file is:
file object = open(file_name [, access_mode][, buffering])
As you have not mentioned access_mode(optional), default is 'Read'. But if file 'test.txt' does not exists in the folder where you are executing script, it will through an error as you got.
To correct it, either add access_mode as "a+" or give full file path e.g. C:\test.txt (assuming windows system)
The error is independent from the version, but it is not clear
what you want to do with your file.
If you want to read from it and you get such an error, it means that your file is not where you think it is. In any case you should write a line like testFile = open("test.txt","r").
If you want to create a new file and write in it, you will have a line like
testFile = open("test.txt","w"). Finally, if your file already exists and you want to add things on it, use testFile = open("test.txt","a") (after having moved the file at the correct place). If your file is not in the directory of the script, you will use commands to find your file and open it.
for some reason the readline() function in my following code seems to print nothing.
fileName = input()
fileName += ".txt"
fileA = open(fileName, 'a+')
print("Opened", fileA.name)
line = fileA.readline()
print(line)
fileA.close()
I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!
I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.
Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()
Doing so sets the pointer to the top of the file.
Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.
Answer Has Been Decided
The problem was not listing the entire file listing (i.e. DRIVE1\DRIVE2\...\fileName.txt).
Also, note that the backslashes must be turned into forwardslashes in order for
Python to read it (backslashes are outside of the unicode listing).
Thus, using: addy = 'C:/Users/Tanner/Desktop/Python/newfile.txt'
returns the desired results.
It's been a while since I have played with Python, and for my most recent class, we are required to make a BFS search that does a Word Puzzle that the Alice in Wonderland author created. I am just stating this, as the algorithm is the homework, which I have completed. In other words, my question does not apply to the answer to my homework question.
With that out of the way, I am in need of help on how to open, edit, read, create some form of text files in Python. My real problem is to place a list of words that I have inside of a .txt file, into a Dictionary dictionary. but I would much rather do this myself. Thus, I am left with how to do the said to text files.
NOTE:
I am running v3.3.
All documentation that I have found while searching how to solve this simple problem
is in regards to 2.7 or older.
I have tried to use:
>>> import sys from argv
>>> script, filename = argv
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
I have also tried to use:
>>> f = open(newfile.txt, 'r')
But again, I get this error:
File "<pyshell#8>", line 1, in <module>
f = open (filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'newfile.txt'
However, I am positive that this file does exist. All of this being said, I am not sure if this is a directory problem, a problem understanding, or what... That is, anything would help!
First, if you want to retrieve a file name which is passed as the first argument to your script, use code like this:
import sys
if len(sys.argv) > 2:
filename = sys.argv[1]
else:
# set a default filename or print an error
Secondly, the error clearly indicates that the script can't find the file newfile.txt. So it is either not in the current directory, you don't have the permission to read it, etc...
To open a file for reading, use with command as follows
# This is python 3 code
with open('yourfile.txt', 'r') as f:
for line in f:
print(line)
with command used together with open command has already the raising exception process.