How do i change the location directory of python open document? - python

i was just wondering how i can change the location/directory that python uses to navigate and open files.
I am a super noob so please use small words if you help me, and if you do, thanks.
In case it matter, i use two mass storage devices one is located under the A:\ and the other using the default C:. From memory i installed python under the A drive even though i know some parts are under the C drive. I also believe that i have set my mass storage devices up in AHCI or IDE.
Example Code:
File_Test = open("Test.txt", "r")
This then produces the error:
Traceback (most recent call last):
File "", line 1, in
File_Test = open("Test.txt", "r")
IOError: [Errno 2] No such file or directory: 'Test.txt'"
Which from what i understand is python can't find the directory under which thise file is located.
I would really like to know how to make python locate files in my specified directory. If you can help i would be very appreciative, thanks.

Use the os.chdir() function.
>>> import os
>>> os.getcwd()
'/home/username'
>>> os.chdir(r'/home/username/Downloads')
>>> os.getcwd()
'/home/username/Downloads'
You can get the current working directory using the os.getcwd function. The os.chdir function changes the current working directory to some other directory that you specify. (one which contains your file) and then you can open the file using a normal open(fileName, 'r') call.

More precisely, the problem is that there is no file "Test.txt" in the directory Python considers its current working directory. You can see which directory that is by calling os.getcwd. There are two solutions.
First, you can change Python's working directory by calling os.chdir to be the directory where your file lives. (This is what Sukrit's answer alludes to.)
import os
# Assuming file is at C:\some\dir\Test.txt
os.chdir("C:\some\dir")
file_test = open("Test.txt", "r")
Second, you can simply pass the full, absolute path name to open:
file_test = open("C:\some\dir\Test.txt")

Related

FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'

can someone tell me why when I want to open a text file with python
my output is FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'
even though the file is already in the same folder and the writing is correct.
and this is my code
f = open("demofile.txt", "r")
print(f.read())
thank you before
The path of the Python file and the current working directory can differ. open uses the current working directory if you use a relative path. The obvious fix is to use an absolute path. But then you will have to edit the code each time you copy the script to a different folder.
You can use pathlib to create an absolute path based on the current running scripts location. Put this in a Python script, run it and look at the result.
import pathlib
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'demofile.txt')
print(pathlib.Path(__file__).parent / 'data' / 'demofile.txt')
So your code can be changed to
filepath = pathlib.Path(__file__).parent / 'demofile.txt'
with open(filepath, 'r') as f:
print(f.read())
Try using with
with open("demofile.txt","r") as f:
f.read()
Maybe, You are executing python file with absolute path that's why FileNotFound.
Try with absolute path. Like, c:\files\demofile.txt
I solved the problem with the answer of Mathias, I had the same problem but with an image, then you need to write
import pathlib
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'name_of_your_file.extension')
print(pathlib.Path(__file__).parent / 'data' / 'name_of_your_file.extension')
already done the correct answer is to use the name of the specific folder where the text files are located
thank you very much, everyone

Opening file error in Python : No such file or directory

I'm a newbie for writing here. So please please be bear with me.
I'm running this code to open my file and I put this in right directory 'data'. But my python sent me error message continuely.
I wrote this,
#file = unidecode.unidecode(open('./data/input.txt').read())
#file = unidecode.unidecode(open('./data/linux.txt').read())
file = unidecode.unidecode(open('./data/hh1.txt').read())
file_len = len(file)
print('file_len =', file_len)
and poped up this
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-36-aa7f0f650918> in <module>()
4 #file = unidecode.unidecode(open('./data/linux.txt').read())
5
----> 6 file = unidecode.unidecode(open('./data/hh1.txt').read())
7 file_len = len(file)
8 print('file_len =', file_len)
FileNotFoundError: [Errno 2] No such file or directory: './data/hh1.txt
code image
directory
It's part of RNN(Recurrent Neural Network) code and it's part of processing text data to learn knitting pattern.
It's very simple error but I can't find a good way out.... So thank you for your patient to read this and I hope someone could help me out
You're trying to open a file that is inside data folder in your relative path.
open('./data/hh1.txt').read()
If your script is in
/home/user/test.py
This one tries to open:
/home/user/data/hh1.txt
And if you use
open('./hh1.txt').read()
This one tries to open
/home/user/hh1.txt
That is in the same directory of your script.
You can use:
import os
print(os.listdir())
And it will show you all files in the current directory.
If you're using a relative path, check the path from your current directory to the destination file.
It's likely that the path that you have entered is being interpreted differently than expected. This depends on a variety of this such as where the Python file you are executing is and whether it is part of a bigger project.
A good way to debug this is to expand the path you are trying to use into its absolute path. You can do this using the following code:
import os
print(os.path.abspath("./data/hh1.txt"))
This will output something like "/home/user/project/data/hh1.txt".
You can check the output of this and verify that your files are in the right location or if your path is possibly incorrect.

How to fix "No such file or directory" error with csv creation in Python

I'm trying to make a new .csv file, but I'm getting a "No such file or directory" in the with open(...) portion of the code.
I modified the with open(...) portion of the code to exclude a direction, substituting a string name, and it worked just fine. The document was created with all my PyCharm scratches on the C Drive.
I believe it's worth noting that I'm running python on my C: Drive while the directory giving me issues exists on the D: Drive. Not sure if that actually makes a difference, but i
path = r"D:\Folder_Location\\"
plpath = pathlib.PurePath(path)
files = []
csv_filename = r"D:\Folder_Location\\"+str(plpath.name)+".csv"
#Create New CSV
with open(csv_filename, mode='w',newline='') as c:
writer = csv.writer(c)
writer.writerow(['Date','Name'])
I expected the code to create a new .csv file that would then be used by the rest of the script in the specific folder location, but instead I got the following error:
File "C:/Users/USER/.PyCharm2018.2/config/scratches/file.py", line 14, in <module>
with open(csv_filename, mode='w',newline='') as c:
FileNotFoundError: [Errno 2] No such file or directory: '[INTENDED FILE NAME]'
Process finished with exit code 1
The error code correctly builds the file name, but then says that it can't find the location, leading me to believe, again, that it's not the code itself but an issue with the separate drives (speculating). Also, line 14 is where the with open(...) starts.
EDIT: I tested a theory, and moved the folder to the C: drive, updated the path with just a copy and paste from the new location (still using the \ at the end of the file path in Python), and it worked. The new .csv file is now there. So why would the Drive make a difference? Permission issue for Python?
The raw string can not end with one single backslash '\' so what you are using in your code like in path = r"D:\Folder_Location\\" is the right thing but actually you don't need any backslashes at the end of your path:
i ran some similar tests like yours and all goes well, only got the same error when i used a non existing directory
this is what i got:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\python\\myProgects\\abc\\\\sample3.txt'
so my bet is you have a non existing path assigned in path = r"D:\Folder_Location\\" or your path is referring to a file not a folder
to make sure just run this:
import os
path = r"D:\Folder_Location\\"
print(os.path.isdir(path)) # print true if folder already exists
better approach:
file_name = str(plpath.name)+".csv"
path = r"D:\Folder_Location"
csv_filename = os.path.join(path, file_name)

python: zipfile.ZipFile No such file or directory

There is folder path:
P:\\2018\\Archive\\
There are many zipfiles I want to create programmatically, but am starting with test. I will name this test zip file "CO_007_II.zip" and will attempt to create in above location:
import zipfile as zp
with zp.ZipFile("P:\\2018\\Archive\\CO_007_II.zip",'w') as myzip:
myzip.write(r"P:\2018\CO_007_II")
But I get error!
...
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'P:\\2018\\Archive\\CO_007_II.zip'
Is this not method for creating new zipfile? I know file does not exist. Is why I am using 'w' mode, no?
This is documentation:
https://docs.python.org/3/library/zipfile.html
It says:
'w' to truncate and write a new file
Example on documentation page:
with ZipFile('spam.zip', 'w') as myzip:
myzip.write('eggs.txt')
code worked two days ago to create new zip file but did not add folder. Today nothing works! Why not? All paths valid. How do I create new zip file with python and add folders to it?
I also encountered a similar issue and came here looking for answers. Since this was the top hit, I'll add what I discovered.
The answer provided by #metatoaster didn't work for me, when stepping through the code I found that the path returned true to isdir.
In my case, the path length exceeded the Windows max path length (260 chars) which was causing it to fail despite the folder path being valid.
Hope that helps someone else down the line!
The only way this could be reproduced was to create a zipfile in a directory that does NOT exist yet. The only way to be sure (you cannot trust a file manager; only way to verify is to check from within the program itself) is to assign the desired path of the new zip file to a variable (e.g. path), and then call isdir(dirname(path)). For example:
from os.path import isdir
from os.path import dirname
target = "P:\\2018\\Archive\\CO_007_II.zip"
if not isdir(dirname(target)):
print('cannot create zipfile because target does not exists')
else:
# create the zipfile
I had the same issue. It was the long path. I solved by adding this //?/C at the beginning of the path
path = r"//?/C:\Users\Camilo\Proyectos"

Python - Sort files in directory and use latest file in code

Long time reader, first time poster. I am very new to python and I will try to ask my question properly.
I have posted a snippet of the .py code I am using below. I am attempting to get the latest modified file in the current directory to be listed and then pass it along later in the code.
This is the error I get in my log file when I attempt to run the file:
WindowsError: [Error 2] The system cannot find the file specified: '05-30-2012_1500.wav'
So it appears that it is in fact pulling a file from the directory, but that's about it. And actually, the file that it pulls up is not the most recently modified file in that directory.
latest_page = max(os.listdir("/"), key=os.path.getmtime)
cause = channel.FilePlayer.play(latest_page)
os.listdir returns the names of files, not full paths to those files. Generally, when you use os.listdir(SOME_DIR), you then need os.path.join(SOME_DIR, fname) to get a path you can use to work with the file.
This might work for you:
files = [os.path.join("/", fname) for fname in os.listdir("/")]
latest = max(files, key=os.path.getmtime)
cause = channel.FilePlayer.play(latest)

Categories

Resources