python finding file error with wrong file referenced [duplicate] - python

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
I have isolated a problematic part of my code and run it as 3 lines (see below), yet I still get this weird error where python tells me I used invalid argument, which looks different than the argument passed in. It apparently at random replaces one of my backslashes by double back slash (which shouldn't matter) and alters the name of the file i want opened.
Code:
fl = open("D:\test\sysi\temporary\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
Error:
OSError: [Errno 22] Invalid argument: 'D:\test\\sysi\temporary\x0ce_in.txt'
Anybody has encountered this? Any ideas what could be causing this or what could I try? (I have already deleted and re-created the file in question thinking it could be corrupted, didn't change anything)

I tested it and I needed to use double slash "\\" to use this without your error:
fl = open("D:\\test\\sysi\\temporary\\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
I believe it is because a single slash will be used as an escape character.
We do not know if your file is corrupted as you suspected in you question since the argument to "open" already was invalid. Your textfile was never opened before the error.
Now I only get, "[Errno 2] No such file or directory: 'D:\test\sysi\temporary\fe_in.txt'" because I did not place a file like yours in my file system, but if you have it the program should succeed.

try:
open(r"D:\test\sysi/temporary\fe_in.txt","r")
or
open(r"D:/test/sysi/temporary/fe_in.txt","r")
or
path = r"D:\test\sysi\temporary\fe_in.txt"
surely someone will work

Related

File Not Found trying to open CSV using Pandas [duplicate]

This question already has answers here:
FileNotFoundError: [Errno 2] No such file or directory [duplicate]
(6 answers)
Closed 1 year ago.
I am having a small issue that I cannot seem to solve. My program requires the user to input a path to a .csv file and then the program does stuff with it. Here is my code:
import pandas as pd
path = input("Please enter a path to a .csv file")
data = pd.read_csv(path)
I am running it in my terminal, so dragging the file into it yields what I believe to be the absolute path. The path looks like /Users/me/Downloads/sample.csv and the error message is FileNotFoundError: [Errno 2] File b'/Users/me/Downloads/sample.csv ' does not exist: b'/Users/me/Downloads/sample.csv '
I attempted to concatenate an r in front of it so that it would treat it as a raw string (that's what my google search yielded) but that just put r's in the path. So my question is where are these b's coming from before the path and how do I make this variable path work?
To answer your question: the b prefix indicates that your path value is a byte literal, not a string.
Taking a look at the available Pandas documentation, it seems like read_csv expects a string value for the path. Although it may accept a byte literal value, it may not be able to handle it in an expected way.
This answer provides a good distinction between strings (sequences of characters) and byte literals (sequences of bytes), and this one demonstrates one way you could decode your byte-literal into a string value

How to handle windows path in Python? [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 15 days ago.
The requirement of code is I have to take the file path from the user in the console and perform some action on that file. Users can give paths in windows style or mac style. for the mac or Linux, the path code is working fine but for the windows path its give an error (because of ) how to handle this error as I can't use the 'r' string in that as it's coming from the user.
user_path = input('give text file path: ')
file = open(user_path, 'r')
words = file.read().split()
print('total number of words: ', len(words))
And if I provide path: C:\desktop\file.txt
its give error
Use C:\\desktop\\file.txt instead of C:\desktop\file.txt.
The error is due to the fact that python is recognizing '\f' in 'C:\desktop\file.txt' as the form feed escape sequence.
It can simply be resolved by using forward slash '/' instead of backslash while providing input.

Can't send an .exe file over flask [duplicate]

This question already has answers here:
Parsing a mix of Backward slash and forward slash in a filename
(3 answers)
Closed 5 years ago.
When I am trying to send a .exe file using send_file() function of Flask (python 2.7) I get this error
IOError: [Errno 22] invalid mode ('rb') or filename:
'C:\\Users\\Dell\\Desktop\\mom\x08uild\\s6\\s6.exe'
where s6.exe is my file I want to send
The \x08 in mom\x08uild is a backspace. That's probably not what you intended: backspaces are not valid in normal Windows filenames, hence the 'invalid filename' error.
It's a bit hard to know for sure without seeing the code, but you might have forgotten to escape a backslash somewhere, causing a \b to appear (which also means backspace).

Python OSError while attempting os.mkdir [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 7 months ago.
import os
directory=input("Directory: ")
if not os.path.exists(directory):
os.mkdir(directory)
os.mkdir(str(directory)+'\steamCMD')
os.mkdir(str(directory)+'\temporary')
A snippet from my code. Returns OSError on the last line shown here. Why? Does exactly same thing as 5th line yet 5th line works like a charm.
Error:
os.mkdir(str(directory)+'\temporary')
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'c:\\testing\temporary'
Similar: Python - os.rename() - OSError: [WinError 123]
os.mkdir(path) returns OSError when directory does not exist
However he had different mistake to me. Anyone tell me why this is happen?
Try:
os.mkdir(str(directory) + '\\temporary')
Or
os.mkdir(str(directory) + r'\temporary')
About the two \\ or r'\temporary', here is the documentation and here is a good question.
Also, os.path.join() is a good choice because which uses \\ on Windows but / on *nix. For example:
os.mkdir(os.path.join(directory), 'temporary')
This gives directory\temporary on Windows and directory/temporary on *nix. It is a more clear and simple way.

File not found Error in reading text in python [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
I am trying to read a text file on my hard drive via python with the following script:
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
But it is giving the following error:
IOError Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'
I also tried with other way:
with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
print f.read()
Ended up with the same error. The text file is present in the directory specified.
Replace
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
with
fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.
Another way to do it without a raw string is
fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")
This escapes the backslashes (i.e. "\\" => \).
An even better solution is to use the os module:
import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')
This creates your path in an os-independent way so you don't have to worry about those things.
One last note... in general, I think you should use the with construct you mentioned in your question... I didn't in the answer for brevity.
I was encountering same problem. This problem resulted due to different file path notation Python.
For example, filepath in Windows reads with backward slash like: "D:\Python\Project\file.txt"
But Python reads file path with forward slash like: "D:/Python/Project/file.txt"
I used r"filepath.txt" and "os.path.join" and "os.path.abspath" to no relief. os library also generates file path in Windows notation. Then I just resorted to IDE notation.
You don't encounter this error if "file.txt" is located in same directory, as filename is appended to working directory.
PS: I am using Python 3.6 with Spyder IDE on Windows machine.

Categories