Path error in python - python

I have written a script to rename a file
import os
path = "C:\\Users\\A\\Downloads\\Documents\\"
for x in os.listdir(path):
if x.startswith('i'):
os.rename(x,"Information brochure")
When the python file is in a different directory than the path I get a file not found error
Traceback (most recent call last):
File "C:\Users\A\Desktop\script.py", line 5, in <module>
os.rename(x,"Information brochure")
FileNotFoundError: [WinError 2] The system cannot find the file specified:'ib.pdf'-> 'Information brochure'
But if I copy the python file to the path location it works fine
import os
for x in os.listdir('.'):
if x.startswith('i'):
os.rename(x,"Information brochure")
What is the problem?

Your variable x is currently only the filename relative to path. It's what os.listdir(path) outputs. As a result, you need to prepend path to x using os.path.join(path,x).
import os
path = "C:\\Users\\A\\Downloads\\Documents\\" #os.path.join for cross-platform-ness
for x in os.listdir(path):
if x.startswith('i'): # x, here is the filename. That's why it starts with i.
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))

The x variable has the name of the file but not the full path to the file. Use this:
os.rename(path + "\\" + x, "Information brochure")

Related

how to rename a file using python?

If the name is too long in the folder, there will be a problem, so I'm working on a code to change it at once. There's an error.
import os
import pathlib
p_dir = './data/'
for file in os.listdir(p_dir):
oldname = file
newname = file.split('_')[5] + '_SmmLogs.zip'
os.rename(oldname, newname)
I tried it like this, and from what I see, there seems to be no problem.
but..
Traceback (most recent call last): File "d:/Coding/name/namechange.py", line 15, in os.rename(oldname, newname) FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。: 'PN8B744_M0001_NewMDCR_4x4mmP_AllatOnce_20220328000119153_SmmLogs.zip' -> '20220328000119153_SmmLogs.zip
There's an error like this. Is there any way...?
listdir returns a list of filenames. You need to add the path p_dir to your filenames
for file in os.listdir(p_dir):
file_name = file
oldname = str(file_name)
newname1 = file.split('_')[5] + '_SmmLogs.zip'
newname = str(newname1)
os.rename(os.path.join(p_dir,oldname), os.path.join(p_dir,newname))

Python File Not Found Error even though file is in same directory

I'm running a python code (filename- images.py) that reads-
import gzip
f = gzip.open('i1.gz','r')
But it is showing the FileNotFoundError.
My folder containing images.py looks like-
New Folder/
images.py
i1.gz
(...Some other files...)
The problem is that you are not running the script from within the New Folder.
You can easily solve it by using the absolute path without hard-coding it:
from os import path
file_path = path.abspath(__file__) # full path of your script
dir_path = path.dirname(file_path) # full path of the directory of your script
zip_file_path = path.join(dir_path,'i1.gz') # absolute zip file path
# and now you can open it
f = gzip.open(zip_file_path,'r')
Check the current working directory of the script by doing:
import os
os.getcwd()
Then, compare this with your i1.gz absolute path. Then you should be able to see if there are any inconsistencies.
Are you run the script from the New Folder?
If you are in the folder, it should work:
c:\Data\Python\Projekty\Random\gzip_example>python load_gzip.py
but if you run the script from a parent folder with the folder name, it returned the error:
c:\Data\Python\Projekty\Random>python gzip_example\load_gzip.py
Traceback (most recent call last):
File "C:\Data\Python\Projekty\Random\gzip_example\load_gzip.py", line 2, in <module>
f = gzip.open('file.gz', 'r')
File "C:\Python\Python 3.8\lib\gzip.py", line 58, in open
binary_file = GzipFile(filename, gz_mode, compresslevel)
File "C:\Python\Python 3.8\lib\gzip.py", line 173, in __init__
fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'file.gz'
The way I usually set working directory and work with files is as follow:
import os
pwd_path= os.path.dirname(os.path.abspath(__file__))
myfile = os.path.join(pwd_path, 'i1.gz')

File exists but open says it doesnt

dir_path = os.path.dirname(os.path.realpath(__file__))
from os.path import isfile, join
onlyfiles = [f for f in listdir(dir_path) if isfile(join(dir_path, f))]
print(onlyfiles);
with open("config.json", 'r') as jsondata:
config = json.loads(jsondata.read())
Running this code, somehow, triggers a non existing error despite the file being listed during
print(onlyfiles);
Here is the full output log from the console.
Traceback (most recent call last):
['builder.py', 'builder.spec', 'builderloader2.rb', 'config.json',
'Run.bat', 'Run.bat.lnk', 'test.json']
File "C:/Users/cody.jones/Desktop/Builder Generator Release/builder.py",
line 26, in <module>
with open("config.json", 'r') as jsondata:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
Process finished with exit code 1
provide full path to open() instead of just file name as by default it will look for file in same directory
try:
open(r"C:/Users/cody.jones/Desktop/Builder Generator Release/config.json", "r")
The script will look for config.json in the current working directory - which presumably is not the same as the folder that the script resides in.
Update your open call to include the path you've already generated.
with open(os.path.join(dir_path, "config.json"), 'r')) as jsondata:
By doing it this way (rather than just including the absolute path) this script will still work if you move it to a different directory or computer so long as you keep the script and config together.

Python - Can't locate downloaded file to unzip

Using selenium, I was able to automate the download of a zip file and save it to a specified directory. When I try to unzip the file, however, I hit a snag where I can't seem to locate the recently downloaded file. If it helps, this is the block of code related to the downloading and unzipping process:
# Click on Map Link
driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Map\"]").click()
# Download Data
driver.find_element_by_xpath('//*[#id="buttons"]/a[4]/img').click()
# Locate recently downloaded file
path = 'C:/.../Download'
list = os.listdir(path)
time_sorted_list = sorted(list, key=os.path.getmtime)
file_name = time_sorted_list[len(time_sorted_list)-1]
Specifically, this is my error:
Traceback (most recent call last):
File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-89-3f1d00dac284>", line 3, in <module>
time_sorted_list = sorted(list, key=os.path.getmtime)
File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'grid-m1b566d31a87cba1379e113bb93fdb61d5be5b128.zip'
I tried troubleshooting the code by deleting it and placing another file in the directory, and I was able to find the random file, but not the recently downloaded file. Can anyone tell me what's going on here?
First of all, do not use list for a variable name. That hides the list constructor from being readily available to use somewhere else in your program. Second, os.listdir does not return the full path of the files in that directory. If you want the full path, there are two things you can do:
You can use os.path.join:
import zipfile
path = 'C:/.../Download'
file_list = [os.path.join(path, f) for f in os.listdir(path)]
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]
myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
with myzip.open(contained_file) as f:
# save data to a CSV file
You can also use the glob function from the glob module:
from glob import glob
import zipfile
path = 'C:/.../Download'
file_list = glob(path+"/*")
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]
myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
with myzip.open(contained_file) as f:
# save data in a CSV file
Either should work.

Python File Renaming Issue

import os
for filename in os.listdir("."):
if not filename.startswith("renamefilesindir"):
for filename2 in os.listdir(filename):
if filename2.startswith("abcdefghij"):
newName = "[abcdefghij.com][abcde fghij][" + filename + "][" + filename2[11:16] + "].jpg"
print(filename2)
print(newName)
os.rename(filename2, newName)
I have a folder with a few hundred other folders inside of it. Inside each secondary folder is a number of files all similarly named. What I want to do is rename each file, but I get the following error whenever I run the above program.
abcdefghij_88741-lg.jpg
[abcdefghij.com][abcde fghij][3750][88741].jpg
Traceback (most recent call last):
File "C:\directory\renamefilesindir.py", line 9, in <module>
os.rename(filename2, newName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'abcdefghij_88741-lg.jpg' -> '[abcdefghij.com][abcde fghij][3750][88741].jpg'
I don't know what this means. It prints the existing file name, so I know it's found the file to be changed. Am I renaming the file wrong? What can't it find?
os.listdir contains just the names of the files and not the full paths. That's why your program actually tried to rename a file inside your current directory and it failed. So you could do the following:
import os.path
os.rename(os.path.join(filename, filename2), os.path.join(filename, newName))
since file with name filename2 is inside directory with name filename.

Categories