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

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

Related

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.

python finding file error with wrong file referenced [duplicate]

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

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 error: "cannot find path specified" [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 22 days ago.
import os
import random
os.chdir("C:\Users\Mainuser\Desktop\Lab6")
#Am i supposed to have a os.chdir?
# I think this is what's giving the error
#how do i fix this?
def getDictionary():
result = []
f = open("pocket-dic.txt","r")
for line in f:
result = result + [ line.strip() ];
return result
def makeText(dict, words=50):
length = len(dict)
for i in range(words):
num = random.randrange(0,length)
words = dict[num]
print word,
if (i+1) % 7 == 0:
print
Python gives me an error saying it cannot find the path specified, when i clearly have a folder on my desktop with that name. It might be the os.chidr?? what am i doing wrong?
Backslash is a special character in Python strings, as it is in many other languages. There are lots of alternatives to fix this, starting with doubling the backslash:
"C:\\Users\\Mainuser\\Desktop\\Lab6"
using a raw string:
r"C:\Users\Mainuser\Desktop\Lab6"
or using os.path.join to construct your path instead:
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")
os.path.join is the safest and most portable choice. As long as you have "c:" hardcoded in the path it's not really portable, but it's still the best practice and a good habit to develop.
With a tip of the hat to Python os.path.join on Windows for the correct way to produce c:\Users rather than c:Users.
Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:\Users\Mainuser\Desktop\Lab6" (note the r before the opening quote).

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