To be more user friendly, I have created a prompt for the user to input a file path.
print('Please enter file path surrounded by quotes.')
path = 'r' + input()
df = pd.DataFrame(pd.read_csv(path, index_col=False))
When input is
"C:\path\somefile.csv"
Output returns
FileNotFoundError: [Errno 2] File b'r"C:\path\somefile.csv"' does not exist: b'r"C:\path\somefile.csv"'
If I remove the variable input and drop the file directly into the read_csv argument, it works just fine. Can someone educate me?
You were over-engineering your code. It's as simple as this:
print('Please enter file path without quotes.')
path = input()
df =pd.read_csv(path, index_col=False)
You don't need the quotes, as they will be added automatically
I think you are confusing raw string literals with a string value. When we write something like
csv = pd.read_csv(r'C:\path\somefile.csv')
the r'C:\path\somefile.csv' is a string literal. This is how we represent the string in python code. The user should never be aware of the r'' notation, including both the letter r and the quotes. Instead, they should just type the path as they see it in other programs. This means that you can just do
path = input()
Also the user shouldn't be required to type any quotes.
Related
I am writing a function and my input parameter is the file path: C:\Users\HP\Desktop\IBM\New folder
def read_folder(pth):
for fle in Path(pth).iterdir():
file_name = Path(pth) / fle
return file_name
For me to use this function, I need to specify r'' in the file path, ie.
read_folder(r'C:\Users\HP\Desktop\IBM\New folder')
Is there a way where I can avoid specifying r'' in the file path, ie. like the below and the code would work.
read_folder('C:\Users\HP\Desktop\IBM\New folder')
The reason why I want to do this is so to make it easier for the user to just copy and paste the directory path into the function and just run the function. So it's more for ease-of-use on the user end.
Many thanks.
You can't really do that because without prepending r to your string there's no way python interpreter would know that your string contains \ intentionally and not on purpose to escape the characters.
So you've to either use r"C:\Users\HP\Desktop\IBM\New folder" or "C:\\Users\\HP\\Desktop\\IBM\New folder" as argument while calling read_folder function.
You can escape the backslashes:
read_folder('C:\\Users\\HP\\Desktop\\IBM\New folder')
I'm writing this simple code:
file = input('File to read: ')
fhand = open(file, 'r')
The file I want to open is called 'test.txt', and it is located in a subfolder; what I put into the requested input therefore is: 'DB\test.txt'.
Well: it doesn't work, returning this error message:
OSError: [Errno 22]Invalid argument: 'DB\test.txt'.
I have another file in the same directory, called 'my_file.txt', and I don't get errors attempting to open it. Lastly I have another file, called 'new_file.txt', and this one also gets me the same error.
What seems obvious to me is that the open() function reads the "\t" and the "\n" as if they were special characters; searching on the web I found nothing that really could help me avoiding special characters within user input strings...
Could anybody help?
Thanks!
you'll have no problems with Python 3 with your exact code (this issue is often encountered when passing windows literal strings where the r prefix is required).
With python 2, first you'll have to wrap your filename with quotes, then all special chars will be interpreted (\t, \n ...). Unless you input r"DB\test.txt" using this raw prefix I was mentionning earlier but it's beginning to become cumbersome :)
So I'd suggest to use raw_input (and don't input text with quotes). Or python version agnostic version to override the unsafe input for python 2 only:
try:
input = raw_input
except NameError:
pass
then your code will work OK and you got rid of possible code injection in your code as a bonus (See python 2 specific topic: Is it ever useful to use Python's input over raw_input?).
I am trying to replace an inputted paths' "\" with "/" to avoid a escaping character that messes with my code.
path = input("Enter the Directory: )
path.replace('\' , '/')
First off the reason I want to do this is because when the user inputs the path (copying and pasting it from Windows Explorer), it is in the C:\User\Folder convention which is giving me issues later on in my program when I have to output the real path and it gives me C:\User\Folder with double "\" because of the raw string method.
My path.replace() is not working because the '\' is thinking it is an escaping character. I also tried:
path.replace((r'\'), '/')
But the entire input turns into a string and does not work. Anyone have advice to do this, or another way to get an inputted path that is copied to have / instead of \? Thanks!
replace returns a copy of the string, you'll need to assign the result to the variable
path = input("Enter the Directory: ")
path = path.replace('\\' , '/')
Try using this:
path.replace('\\', '/')
I have a function in a python code whose argument is as follows:
save_geometry(r"""C:\Users\User0\Documents\test.txt """)
I want to modify the argument and be able to save to a different path with a different filename:
filename = "geometries.txt "
filepath = "D:/AllData/"
filefullpath = filepath + filename
Could someone help me how I should pass filefullpath to save_geometry? If there were no r in the argument of save_geometry, it would be easy. But I don't know how to deal with this r.
The r"" construct just tells Python that whatever's in the string should be interpreted as raw data.
"qw\n" == 'qw\n'
r"qw\n" == 'qw\\n'.
It's used because the "\" path separator is also used for newlines and such. You can skip it when putting in the argument; save_geometry(filefullpath) should do what you expect.
Note that the canonical way of putting together paths is os.path.join
path = os.path.join("D:\\", "AllData", "geometries.txt")
User3757614's answer addresses your concern of the raw string notation, but succinctly all the r"" notation does is tell Python that the following string should not treat \ as an escape character, but as a literal backslash. This is important since "C:\new folder" is actually
C:
ew folder
Since \n is a newline.
You cans use the os module to split your string into a folder path and file name.
e.g.
import os
pathname = os.path.dirname('C:\Users\User0\Documents\test.txt') #C:\Users\User0\Documents
filename = os.path.basename('C:\Users\User0\Documents\test.txt') #test.txt
Though you'll need to modify your path string because your \s will be interpreted and newline bytes
i had created a python program but it was not working. this program would take in the input for a file and then display the file contents . the only error i was getting is a syntax error well i could not find the error . Please help me .
the code was :-
nm = input(“enter file name “)
str = raw_input(“enter ur text here: \n”)
f = open(nm,”w”)
f.write(str)
f.close()
print “1.See the file\n”
print “2.Exit\n”
s = input(“enter ur choice “)
if s == 1 :
fi = open(nm,”r”)
cont = fi.read()
for i in cont:
print i
else :
print “thank you “
The problem is that you are reading the filename using input() instead of raw_input(). See this answer that explains:
If you use input, then the data you type is is interpreted as a Python
Expression which means that you end up with gawd knows what type of
object in your target variable, and a heck of a wide range of
exceptions that can be generated. So you should NOT use input unless
you're putting something in for temporary testing, to be used only by
someone who knows a bit about Python expressions.
raw_input always returns a string because, heck, that's what you
always type in ... but then you can easily convert it to the specific
type you want, and catch the specific exceptions that may occur.
Hopefully with that explanation, it's a no-brainer to know which you
should use.
Also, since you are reading in the file contents by using fi.read(), your for loop for i in cont: will select each character of the file's contents one at a time, instead of each line. Something to be aware of!