IOError: [Errno 2] No such file or directory [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 9 years ago.
im having problems trying to run an iteration over many files in a folder, the files exist, if I print file from files I can see their names...
Im quite new to programming, could you please give me a hand? kind regards!
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
fdf = open(file, "r")
IOError: [Errno 2] No such file or directory: 'FDF_20110612_140613_...........txt'

You need to prefix each file name with path before you open the file.
See the documentation for os.walk.
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
filepath = os.path.join(path, file)
print filepath
fdf = open(filepath, "r")

Try this:
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
with open(os.path.join(path, file)) as fdf:
# code goes here.

Related

Python, Tried making a script which takes all directorys and renames all the files in them

I tried making an python script which gets all directorys then
goes to the directorys and changes all the files name to the directory name.
The error :
Traceback (most recent call last):
File "D:\assets\steamcmd\yus.py", line 24, in <module>
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
FileNotFoundError: [WinError 2] Nie można odnaleźć określonego pliku (cannot find file): 'steamapps\\workshop\\content\\573090\\2138774925\\.crash' -> 'steamapps\\workshop\\content\\573090\\2138774925\\2138774925
Code below which was used :
import os
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
files = os.listdir()
pathy = os.path.join(directory, f)
for index,file in enumerate(files):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
Eventually, i found the error and have fixed the code.
The problem was : I used os.listdir the wrong way.
Heres the fixed code which i used :
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
pathy = os.path.join(directory, f)
for file in os.listdir(pathy):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(os.path.join(os.path.join(directory, f), file), os.path.join(pathy, pathname+str(file_extension)))

python seach file in directory - unable to open file [duplicate]

This question already has an answer here:
Using os.walk to find and print names of my files, but unable to open them? Path name issue?
(1 answer)
Closed 1 year ago.
I have file list:
import os
import fnmatch
files_template = ['a.txt','b.txt','c.txt','d.txt','e.txt','f.txt']
dir_path = '/users/john'
I need to open file specified in "files_template" list and parse its data but I am able to open the file
for root, dirs, files in os.walk(dir_path):
for file in files:
if file in files_template:
with open(file, 'r') as fh:
str = fh.read()
print(str)
I am getting below error message.
Traceback (most recent call last):
with open(file, 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'
how to fix it?
abs_file_path = os.path.join(root, file)
with open(abs_file_path, 'r') as fh:
...

Extracting zip files using python

I'm trying to get all zip files in a specific directory name "downloaded" and to extract all of their content to a directory named "extracted".
I don't know why, after I'm iterating only existing files name, I get an error that there is no such file...
allFilesList = os.listdir(os.getcwd()+"/downloaded")
print allFilesList #verify - correct expected list
from zipfile import ZipFile
os.chdir(os.getcwd()+"/extracted/")
print os.getcwd() #verify - correct expected dir
for fileName in allFilesList:
print fileName
with ZipFile(fileName, 'r') as zipFileObject:
if os.path.exists(fileName):
print "Skipping extracting " + fileName
continue
zipFileObject.extractall(pwd='hello')
print "Saving extracted file to extracted/",fileName
print "all files has been successfully extracted"
Error message:
File "program.py", line 77, in <module>
with ZipFile(fileName, 'r') as zipFileObject:
File "/usr/lib/python2.7/zipfile.py", line 779, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'zipFile1.zip'
You're getting the list of filenames from one directory, then changing to another, and trying to extract the files from that directory that likely don't exist:
allFilesList = os.listdir(os.getcwd()+"/downloaded")
# ...
os.chdir(os.getcwd()+"/extracted/")
# ...
with ZipFile(fileName, 'r') as zipFileObject:
If you change that file ZipFile command to something like this:
with ZipFile(os.path.join("..", "downloaded", fileName), 'r') as zipFileObject:
You should be able to open the file in the directory you found it in.

Renaming a directory in Python [duplicate]

This question already has an answer here:
How to rename files using os.walk()?
(1 answer)
Closed 5 years ago.
I'm trying to rename a directory in Python, such hat the directory will be renamed to its first 8 characters of its original name.
This is what I did:
import os
path = '/home/directories'
for root, dirs, files in os.walk(path):
for directory in dirs:
new_name = directory[0:8]
os.rename(directory, new_name)
I however get the following error:
Traceback (most recent call last):
File "xyz.py", line 8, in <module>
os.rename(directory, new_name)
OSError: [Errno 2] No such file or directory
How can I solve this error?
Thanks.
You need to specify full path of directory
import os
path = 'C:\\Users\\demo_test_eg'
for root, dirs, files in os.walk(path):
for directory in dirs:
new_name = directory[0:8]
path1 = path + "\\"+ directory#Full path of directory
new_path = path + "\\"+new_name#Full path of file whose name is changed
os.rename(path1, new_path)
Note :
I have added "\\" for windows

Python IOError: [Errno 2] from recursive directory call

The code below is part of a program I am writing that runs a method on every .py, .sh. or .pl file in a directory and its folders.
for root, subs, files in os.walk("."):
for a in files:
if a.endswith('.py') or a.endswith('.sh') or a.endswith('.pl'):
scriptFile = open(a, 'r')
writer(writeFile, scriptFile)
scriptFile.close()
else:
continue
When writing the program, it worked in the directory tree I wrote it in, but when I moved it to another folder to try it there I get this error message:
Traceback (most recent call last):
File "versionTEST.py", line 75, in <module>
scriptFile = open(a, 'r')
IOError: [Errno 2] No such file or directory: 'enabledLogSources.sh'
I know something weird is going on because the file is most definitely there...
You'll need to prepend the root directory to your filename
scriptFile = open(root + '/' + a, 'r')
files contains only the file names, not the entire path. The path to the file can be obtained by joining the file name and the root:
scriptFile = open(os.path.join(root, a), "r")
You might want to have a look at
https://docs.python.org/2/library/os.html#os.walk

Categories