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

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

Related

issue with counting lines of python file

I am traversing a directory, and if python file is found, trying to find the number of lines of code in it.
I am not really sure why I face the below issue.
for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
for file in filenames:
if pathlib.Path(file).suffix == ".py":
num_lines = len(open(file).readlines()) #causes issue
print(
f"Root:{dirpath}\n"
f"file:{file}\n\n"
f"lines: {num_lines}" //
)
Érror:
Traceback (most recent call last):
File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory:
If i remove that line, the code works as expected. There is a single line code within. Any guidance here?
file is the file's name, not its path, to get its full path, join the name with the directory path dirpath using os.path.join. Also, it is better to use a with statement when dealing with files since it automatically closes the file:
file_path = os.path.join(dirpath, file)
with open(file_path) as f:
num_lines = len(f.readlines())
You can also try this way. You have to get the os.path.abspath(file) path of the file then only it'll open.
and always with contect_managers for IO operation.
for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
for file in filenames:
if pathlib.Path(file).suffix == ".py":
try:
with open(os.path.abspath(file)) as f:
print(len(f.readlines()))
print(os.path.abspath(file))
except:
pass

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.

Getting a error: FileNotFoundError: [Errno 2] No such file or directory: while trying to open a file

In a Folder called Assignment Parser, I've my parsing.py file along with a auth.txt file. Trying to open this auth.txt file. But getting an error that says :
(base) C:\Users\Ajay\Desktop\Python\Assignment Parser>python parsing.py
Traceback (most recent call last):
File "parsing.py", line 27, in <module>
main()
File "parsing.py", line 8, in main
file = open(file_path / "auth.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Ajay\\Desktop\\Python\\Assignment Parser\\auth.txt'
Code:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(file_path / "auth.txt","r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
Where is this going wrong? PFA for the screenprint.
Try this:
from pathlib import Path
import os
def main():
# read file
# C:\Users\Ajay\Desktop\Python\Assignment Parser\
file_path = Path("C:/Users/Ajay/Desktop/Python/Assignment Parser/")
file = open(os.path.join(file_path, "auth.txt"), "r")
# file = open("auth.txt", "r")
lines = file.readlines()
file.close()
I think the problem is in file extension, I see parsing has .py extension but auth is not
please try file = open(file_path / "auth", "r") again (just delete .txt extension)
As you have your python file in same folder as your text file. You can directly use below code.
def main():
file = open("./auth.txt")
lines = file.readlines()
file.close()
Also make sure, your syder working directory is set to this folder path "C:/Users/Ajay/Desktop/Python/Assignment Parser"

How to read a content of a file obtained from os.listdir? [duplicate]

This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 3 years ago.
I am trying to read a CSV file. I have two CSVs under two folders. I get the CSV file but when I try to read the content, it says that I dont have such file or directory.
import os
import csv
def scanCSVFile(folder, output_file_name):
myfile = open(output_file_name, "a")
files = os.listdir(folder)
for file in files:
if file.endswith('.csv'): #gives two csv files
with open(file) as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
for line in csvreader:
print (line)
myfile.close()
def openCSV(path):
scanCSVFile("./src/goi","goi.yml")
scanCSVFile("./src/kanji","kanji.yml")
openCSV('.')
Error:
C:\Users\Peace\Documents\LMS>python csvToYaml.py
Traceback (most recent call last):
File "csvToYaml.py", line 26, in <module> openCSV('.')
File "csvToYaml.py", line 24, in openCSV scanCSVFile("./src/goi","goi.yml")
File "csvToYaml.py", line 14, in scanCSVFile with open(file) as csvfile:
FileNotFoundError: [Errno 2] No such file or directory: 'Pro.csv'
You have to delete break from code
import os,glob
folder_path = r'path'
for filename in glob.glob(os.path.join(folder_path, '*.csv')):
with open(filename, 'r') as f:
for line in f:
print(line)
You can read data from csv file using pandas.Data will be stored in dataframes.
".yml" extension is obsolete now. Mostly ".yaml" is used.
The below link shows how to read .yaml files.
How can I parse a YAML file in Python
# loading libraries and reading the data from csv files.
import pandas as pd
market_df = pd.read_csv("./src/goi.csv")
print(market_df)

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

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.

Categories