Opening file path not working in python [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I am writing a database program and personica is my test subject (I would usually have a variable in the place of the file path, but for test and demo purposes I just have a string.). There is a text file at this exact location on my computer (I have changed my username on here, by the way because I am paranoid.), but it says:
Traceback (most recent call last):
File "C:\Users\Admin\Documents\Project
Documentation\InteractiveExecutable.py", line 46, in <module>
ReadPerson = open("C:/Users/Admin/Documents/Project
Documentation/personica.txt", 'r')
IOError: [Errno 2] No such file or directory:
'C:/Users/Admin/Documents/Project Documentation/personica.txt'
This is the line of code:
ReadPerson = open("C:/Users/Admin/Documents/Project Documentation/personica.txt", 'r')
I am certain that it is there and when I copy that address into Windows Explorer, it takes me right to the text file.
Anyone know why this is not working?

The new-ish pathlib module (available in Python >= 3.4) is great for working with path-like objects (both Windows and for other OSes).
It's Paths - Paths all the way down
To simplify: you can build up any path (directory and file path objects are treated exactly the same) as an object, which can be an absolute path object or a relative path object. You can use raw strings to make complex paths (i.e., r'string') and pathlib will be very forgiving. However, note that there are better ways to build up paths than raw strings (see further down).
Here are examples:
from pathlib import Path
Path(r'c:\temp\foo.bar') # absolute path
Path(r'c:/temp/foo.bar') # same absolute path
Path('foo.bar') # different path, RELATIVE to current directory
Path('foo.bar').resolve() # resolve converts to absolute path
Path('foo.bar').exists() # check to see if path exists
Note that if you're on Windows pathlib forgives you for using the "wrong slash" in the second example. See discussion at the end about why you should probably always use the forward slash.
Simple displaying of some useful paths- such as the current working directory and the user home- works like this:
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
To navigate down the file tree, you can do things like this. Note that the first object, home, is a Path and the rest are just strings:
some_person = home/'Documents'/'Project Documentation'/'personica.txt' # or
some_person = home.join('Documents','Project Documentation','personica.txt')
To read a file located at a path, you can use its open method rather than the open function:
with some_person.open() as f:
dostuff(f)
But you can also just grab the text directly!
contents = some_person.read_text()
content_lines = contents.split('\n')
...and WRITE text directly!
data = '\n'.join(content_lines)
some_person.write_text(data) # overwrites existing file
Check to see if it is a file or a directory (and exists) this way:
some_person.is_dir()
some_person.is_file()
Make a new, empty file without opening it like this (silently replaces any existing file):
some_person.touch()
To make the file only if it doesn't exist, use exist_ok=False:
try:
some_person.touch(exist_ok=False)
except FileExistsError:
# file exists
Make a new directory (under the current directory, Path()) like this:
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
Get the file extension or filename of a path this way:
some_person.suffix # empty string if no extension
some_person.stem # note: works on directories too
Use name for the entire last part of the path (stem and extension if they are there):
some_person.name # note: works on directories too
Rename a file using the with_name method (which returns the same path object but with a new filename):
new_person = some_person.with_name('personica_new.txt')
You can iterate through all the "stuff' in a directory like so using iterdir:
all_the_things = list(Path().iterdir()) # returns a list of Path objects
Sidebar: backslashes (\)
Be careful when using backslashes in a path string, especially ending a path with a backslash. As with any string, Python will read that terminating backslash as an escape character even in raw input mode. Observe:
>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
So this will give a pretty cryptic error message if you are not aware of this issue:
>>> Path(r'C:\')
File "<stdin>", line 1
Path(r'\')
^
SyntaxError: EOL while scanning string literal
The reason for this error is that \' is assumed to be a single quotation in the string. This works fine: '\'' (the second single quotation ends the string).
If you insist on using backslashes, be sure to use raw input mode or you will run into problems. For example, the '\t' character represents a tab. So when you do this (without raw input):
>>> Path('C:\temp')
You are putting a tab character into your path. This is perfectly legal and Python won't complain until you do something that causes Windows to try turning it into a real Windows path:
>>> Path('C:\temp').resolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'
This is also a very cryptic error if you do not know what is going on! Best to avoid the backslash characters altogether when messing about with paths.
Preventing Your Problem
Your problem occurred when you created your file and erroneously added a double extension. To prevent this issue using pathlib, use the touch method to make the file:
some_person = Path.home()/'Documents'/'Project Documentation'/'personica.txt'
some_person.touch()

On Windows, I like to use Python's raw string format for file paths:
path = r'C:/Users/Admin/Documents/Project Documentation/personica.txt'
Note the r at the beginning of the string. Also note that the forward slash can be important as well.
Then I can just do the regular Python open() command:
with open(path) as fobj:
for line in fobj:
print line
See the String Literals section in Python's lexical analysis document:
https://docs.python.org/2/reference/lexical_analysis.html#string-literals

Related

FileNotFoundError: [Errno 2] No such file or directory: '9788427133310_urls.csv' [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.
Here's the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
Is test.rtf located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
First check what's your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put '/' instead of ''
with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.

os.path.join accesses file preventing rename operation

I am trying to handle a JSON decode by backing up a malformed file when the decode fails, but I'm experiencing some strange behaviour that I did not expect from the os.path.join method.
The following code fails with an exception: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'file.txt' -> 'file.txt\\.bak'
file_path = "file.txt"
try:
with open(file_path, 'r') as f:
json.load(f)
except json.JSONDecodeError as e:
os.rename(file_path, os.path.join(file_path, '.bak'))
If I change the argument like this: os.rename(file_path, file_path + '.bak') The code executes as expected without the permission error. It seems like the os.path.join method actually accesses the file rather than being a strict string operation. Is this expected behaviour?
os.path.join(file_path, '.bak')) actually will give you file.txt\\.bak like you see in the error code, but file_path + '.bak' gives you the correct file name file.txt.bak
os.path.join appends a separator between it's arguments, hence it ends up adding that separator in your case too
Example in MacOS, you can see that it adds a separator between each of it's arguments. os.path.join is more useful to append directory names, of the full filename with the directory paths.
In [4]: import os
In [5]: os.path.join('filename','.bak')
Out[5]: 'filename/.bak'
In [6]: os.path.join('folder1', 'folder2')
Out[6]: 'folder1/folder2'
The error happens since the Windows OS is trying to make a file .bak in a folder named file.txt, which isn't possible since file.txt is a plain file and not a directory, which is correct.
Using file_path+'.bak creates the file.path.bak correctly in the folder you want, hence you don't see an error there!
The error message is the key. As usually on Windows the cause (because it is being used by another process) is wrong, but the names ('file.txt' -> 'file.txt\.bak') are correct.
Join is not a string concatenation but expects that all path members except the last represent folders. So here you are trying to make a file .bak in a folder named file.txt. It is not possible because file.txt is a plain file and not a directory.
On another hand, when you use os.rename(file_path, file_path + '.bak') you are renaming file.txt to file.txt.bak in the same folder which is allowed by the underlying file system, hence no error.
So the behaviour is exactly what is expected, except for the beginning of the error message.
As I am not a core Microsoft Developper, the following is a wild guess. The number of error given by the system is limited. The rename C function received 2 strings and passed it to the system call for rename. As expected the file system generated an error but as it was neither a physical error nor a file system full error, it just choosed a permission refused cause. Which is not really wrong because it is not allowed to create folders under a plain file. But the message for that error is unfortunately because it is being used by another process which is stupid here

python os module sees items in folder but can't modify them [duplicate]

This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 11 months ago.
I am attempting to create a program that cycles through a list of .txt files and adds their filename and contents to a dictionary. The program is navigating to the folder correctly, and I can even print out a the names of the files in the folder. However, when I try to add the filename and contents to the dictionary I get this error in the console,
Traceback (most recent call last):
File "test.py", line 33, in <module>
user1.append_journal_files(location)
File "test.py", line 21, in append_journal_files
with open(filename, 'r') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'dump.0001.txt'
I am not sure why the files are not being recognized as existing once I try to manipulate them. Thank you all in advance for taking the time to look at this. Please let me know if anything needs to be clarified. I am new to programming and want to make sure I am communicating well. Thanks again.
#Python Version 3.6.5
#imports
import os
#classes
class User():
#Class that models a Revit user
def __init__(self, username):
'''initializes the class with a username, additional info
gathered after initialization'''
self.username = username
self.title = ""
self.journal_log = {}
def append_journal_files(self, directory_in_str):
#appends all items of filetype in folder to dictionary instance.
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
with open(filename, 'r') as file_object:
if filename not in self.journal_log.keys():
self.journal_log[filename] = file_object.readlines()
else:
continue
continue
else:
continue
#begin running program
user1 = User("Christian")
location = 'C:\\Users\Christian Gentry\AppData\Local\Autodesk\Revit\Autodesk Revit 2018\Journals'
user1.append_journal_files(location)
filename is just the base name, like dump.0001.txt.
If you want to open the file, you need either a full path, like C:\Users\Christian Gentry\AppData\Local\Autodesk\Revit\Autodesk Revit 2018\Journals\dump0001.txt. (It could also be a relative path from the current working directory, but it has to be a path that gets you to the file.)
You're already doing that for listdir—you're not just passing Journals and expecting that to work—and it's the same idea here.
The simplest fix is:
pathname = os.path.join(directory, filename)
with open(pathname, 'r') as file_object:
While we're at it:
You've only escaped one of the backslashes in your Windows pathnames. Technically, what you have is correct, because all of the other path components happen to start with letters that aren't valid backslash escapes, but that's really not a good thing to rely on. Either use a raw string literal, escape all the backslashes, or use forward slashes.
You don't need to fsencode the path to pass to listdir and fsdecode the results you get back. If you just pass a string in, Python will automatically encode them appropriately and automatically decode the results for you.
Consider using pathlib instead of os; it's a little easier to understand for novices, its help is a lot easier to navigate, and it makes it harder to get a lot of little things wrong. Before 3.6 it wasn't usable with large chunks of the stdlib, but you're using 3.6, so that doesn't matter.

How do I create and open files through Python?

I have a very elementary question, but I've tried searching past posts and can't seem to find anything that can help. I'm learning about file i/o in Python. All the tutorials I've seen thus far seem to skip a step and just assume that a file has already been created, and just being by saying something like handleName = open('text.txt', 'r'), but this leaves 2 questions unanswered for me:
Do I have to create the file manually and name it? I'm using a Mac, so would I have to go to Applications, open up TextEdit, create and save the file or would I be able to do that through some command in IDLE?
I tried manually creating a file (as described above), but then when I tried entering openfile = open('test_readline', 'r'), I got the error: IOError: [Errno 2] No such file or directory: 'abc'
Regarding the error, I'm assuming I have to declare the path, but how do I do so in Python?
openfile = open('test_readline', 'w')
^^
Opening in write mode will create the file if it doesn't already exist. Now you can write into it and close the file pointer and it will be saved.
To be able to read from any file, the file must exist.Right? Now look here, file I/O has the syntax as shown below:
fp = open('file_name', mode) # fp is a file object
The second argument, i.e mode describes the way in which file will be used. w mode will open any existing file(if it exists) with the name as given in first argument. Otherwise it creates a new file with the same name. Beside, if you are on Windows and want to open a file in binary mode then append b to the mode. Eg. to open file to write in binary mode, use wb. Make a note that if you try to open any existing file in w (writing) mode then the existing file with the same name will be erased. If you want to write to the existing file without getting the old data erased, then use the a mode.It adds the new data at the end of the previous one.
fw = open('file_name','w')
fa = open('file_name','a') # append mode
To know in detail you can refer the doc at
Python File I/O.
I hope this helps!
Python will automatically use the default path.
import os
default_path = os.getcwd() ## Returns the default path
new_path = "C:\\project\\" ## Path directory
os.chdir(path) ## Changes the current directory
Once you change the path, the files you write and read will be in C:\project. If you try and read a project else where, the program will fail.
os.chdir is how you declare or set a path in python.
Do I have to create the file manually and name it?
Do you mean as a user, must you use existing tools to create a file, then return to Python to work on it? No. Python has all the tools necessary to create a file. As already explained by vks in their answer, you must open the file using a mode that will create the file if it doesn't exist. You've chosen read ('r') mode, which will (correctly) throw an error if there is no file to read at the location you've specified, which brings us to...
I'm assuming I have to declare the path, but how do I do so in Python?
If you do not (if you say, e.g., "filename.txt"), Python will look in its current working directory. By default, this is the current working directory of the shell when you invoke the Python interpreter. This is almost always true unless some program has changed it, which is unusual. To specify the path, you can either hardcode it like you're doing to the filename:
open('/full/path/to/filename.txt')
or you can build it using the os.path module.
Example:
I created an empty directory and opened the Python interpreter in it.
>>> with open('test.txt'): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('test.txt', 'w'): pass
...
>>>
As noted, read mode (the default) gives an error because there is no file. Write mode creates a file for us with nothing in it. Now we can see the file in the directory, and opening with read mode works:
>>> os.listdir(os.getcwd())
['test.txt']
>>> with open('test.txt'): pass
...
>>> # ^ No IOError because it exists now
Now I create a subdirectory called 'subdir' and move the text file in there. I did this on the command line but could have just as easily done it in Python:
>>> with open('test.txt'): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('subdir/test.txt'): pass
...
Now we have to specify the relative path (at least) to open the file, just like on the command line. Here I "hardcoded" it but it can just as easily be "built up" using the os module:
>>> with open(os.path.join(os.getcwd(), 'subdir', 'test.txt')): pass
(That is just one way it could be done, as an example.)

Why am I getting a FileNotFoundError? [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.
Here's the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
Is test.rtf located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
First check what's your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put '/' instead of ''
with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.

Categories