Python error: "cannot find path specified" [duplicate] - python

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).

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

Why os.path.join returns result with 2 slashes? [duplicate]

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
How to get rid of double backslash in python windows file path string? [duplicate]
(5 answers)
Closed 1 year ago.
Why does it add 2 '\' instead of 1 '/'?
I am trying to create a cats folder(using Jupyter Notebook) inside the train directory for my model where I will place the cat's images. As it os.path.join returns 2 '\' that is why I am unable to copy/place images there through code. Can anybody help me better understand os.path.join as I have gone through several articles but those were of no help
base_dir = "CNN_Working/cats_and_dogs_small"
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)
train_cats_dir = os.path.join(train_dir, 'cats')
os.mkdir(train_cats_dir)
train_cats_dir
This is what it returns
'CNN_Working\\cats_and_dogs_small\\train\\cats'
instead of one '/' it returns 2 '\'?
Looks like you're working on a Windows system.
Running your code on MacOS I get:
(base) X 68884371 % python3 script.py
CNN_Working/cats_and_dogs_small/train
CNN_Working/cats_and_dogs_small/train/cats
When you're running on Windows, the directory seprator is \, not /.
But, because of Python's escaping, when you print it, you see \\, because Python escapes the slash.
Probably you're using Windows and while using Python on It you commonly use double backslashes '\'. On unix systems you'll got the '/'.

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.

'SyntaxError: EOL while scanning string literal' while trying to save file name as argument from command line [duplicate]

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(13 answers)
Closed 3 years ago.
I'm trying to save a file called 'save_as' as an argument from the command line.
import os.path
script, file1, save_as = argv
...snip...
full_path = os.path.join(r "C:\Users\User\Desktop\Folder_Name\", save_as)
Getting error - SyntaxError: EOL while scanning string literal
Any ideas?
Your issue is caused by the path ending: \.
\ is an escape character which escapes ", hence the "EOL" problem, your path is not "closed", the closing " is interpreted as part of the path, so your first parameter closure will never be found. Remove that \ at the end of path elements,
full_path = os.path.join(r "C:\Users\User\Desktop\Folder_Name", save_as)
should work.
Even though, #Trapli is right, I would suggest to start using the pathlib module (new in python 3.4).
>>> from pathlib import WindowsPath
>>> save_as = 'your_file_name.txt'
>>> full_path = WindowsPath('C:/Users/User/Desktop/Folder_Name/') / save_as
>>> str(full_path)
'c:\\Users\\User\\Desktop\\Folder_Name\\your_file_name.txt'
As you can see it has many advantages, for instance:
Don't mess up with backslashes when specifying the path
Joining paths using / operator
Refer to the docs for more https://docs.python.org/3/library/pathlib.html

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