I already have code that works to modify one .edi file (testedifact.edi) in the same directory as my program.
however I need to run my script against a folder containing many of these .edi files so I basically want to use my code to be applied to every single file
here's what I have that works on one file:
segmentsNew = []
global segments
with open( "testedifact.edi" , "r+") as edifactile:
segments = edifactile.readlines()
versionNumber = getVersionNumber(segments)
for segment in segments:
#do stuffs
edifactile.close()
with open ("testedifact.edi" , "w") as edifactfile:
edifactile.writelines(segmentsNew)
edifactfile.close()
but I want to be able to do this for files outside of this directory and also on our network drives..
I've tried iterating through the files in my directory (as a little test) and passing every file to "with open.." like this
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open(file, 'r') as edifactfile:
pass
print(edifactfile.closed)
and I keep getting FileNotFoundError: [Errno 2] No such file or directory: 'testedifact - Kopie (10).edi' though it prints the file name.. what am I doing wrong?
could someone help please?
file only contains the file-name, not the path it is stored in. You need to pass this, too.
path = r'C:\Users\name\test_edi_dir/'
directory = os.listdir(path)
for file in directory:
print("printing file names:", file)
with open(path+file, 'r') as edifactile:
pass
That happens because when you call open(file, 'r') it tries to open a file in the current working directory.
Change your code to this:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass
print(edifactfile.closed)
The next issue is that some files will be actually a directories, and your code may fail with the following error:
traceback (most recent call last):
File "<stdin>", line 3, in <module>
IOError: [Errno 21] Is a directory: '...'
So you want to check if file is actually a file, before opening it:
isFile = os.path.isfile('C:\Users\name\test_edi_dir\' + file)
And finally a complete code is:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
full_filename = 'C:\Users\name\test_edi_dir\' + file
if os.path.isdir(full_filename):
continue
with open(full_filename, 'r') as edifactile:
pass
print(edifactfile.closed)
Looks like you have to pass the entire image path:
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass
Related
This is a school program to learn how to use file and directory in Python. So to do my best I create a function to open, set it as a variable and close properly my file.
But I got the error of the title:
FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'
def load_db():
""" load data base properly
And get ready for later use
Return:
-------
cd : (list) list of tuples
"""
file = open('codedata.pkl', 'rb')
codedata = pickle.loads(file)
file.close()
return codedata
From the interpreter, this is the line
file = open('codedata.pkl', 'rb')
Which is the problem, but I don't see where is the source of the problem.
Can anyone help me?
Can you check what is the location of the file?
If your file is located at /Users/abc/Desktop/, then the code to open the file on python would be as shown below
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
You can also check if the file exists at the desired path by doing something like this
import os
filepath = '/Users/abc/Desktop/codedata.pkl'
if os.path.exists(filepath):
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
else:
print("File not present at desired location")
it happens when you run the script without determining it's the current working directory (example in vs code if you go to Explorer Tape )
You do not work from the same directory that your data.pkl in that's why No file exists
You can know the current directory from getcwd() usually it will be the C/User/.
print(os.getcwd())
filepath=""
if os.path.exists(r"D:\research\StleGAN\karras2019stylegan-ffhq-1024x1024.pkl"):
print("yes")
else:
print("no")
The solution is to open a directory that contains the script or to add the full path.
I am using the OS module to open a file for reading, but I'm getting a FileNotFoundError.
I am trying to
find all the files in a given sub-directory that contain the word "mda"
for each of those files, grab the string in the filename just after two "_"s (indicates a specific code called an SIC)
open that file for reading
will write to a master file for some Mapreduce processing later
When I try to do the opening, I get the following error:
File "parse_mda_SIC.py", line 16, in <module>
f = open(file, 'r')
FileNotFoundError: [Errno 2] No such file or directory:
'mda_3357_2017-03-08_1000230_000143774917004005__3357.txt'
I am suspicious the issue is either with the "file" variable or the fact that it is one directory down, but confused why this would occur when I am using OS to address that lower directory.
I have the following code :
working_dir = "data/"
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
f = open(file, 'r')
I would expect to be able to open the file without issue and then create my list from the data. Thanks for your help.
This should work for you. You need to append the directory because it sees it as just the file name at the top of your code and will look only in the directory where your code is located for that file name.
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
f = open(os.path.join(working_dir, file), 'r')
Also it's a good practice to open files using a context manager of with as it will handle closing your file when it is no longer needed:
for file in os.listdir(working_dir):
if (file.find("mda") != -1):
SIC = re.findall("__(\d+)", file)
with open(os.path.join(working_dir, file), 'r') as f:
# do stuff with f here
You need to append the directory, like this:
f = open(os.path.join(working_dir, file, 'r'))
I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt'
I thought about using the method where you use the full path to open the fileā¦ but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise!
with open('NYT-bestsellers.txt', 'r') as file:
file = file.splitlines()
As Ryan said, every time you open a file by a relative name, you need to make clear for the current work path.
import sys
import os
current_work_directory = os.getcwd() # Return a string representing the current working directory.
print('Current work directory: {}'.format(current_work_directory))
# Make sure it's an absolute path.
abs_work_directory = os.path.abspath(current_work_directory)
print('Current work directory (full path): {}'.format(abs_work_directory))
print()
filename = 'NYT-bestsellers.txt'
# Check whether file exists.
if not os.path.isfile(filename):
# Stop with leaving a note to the user.
print('It seems file "{}" not exists in directory: "{}"'.format(filename, current_work_directory))
sys.exit(1)
# File exists, go on!
with open(filename, 'r') as file:
file = file.splitlines()
If you confirm that the file will be along with your python script file, you can do some preparatory work before opening the file:
script_directory = os.path.split(os.path.abspath(__file__))[0]
print(script_directory)
abs_filename = os.path.join(script_directory, filename)
print(abs_filename)
with open(abs_filename, 'r') as file:
file = file.splitlines()
This current question is building on from this question.
I am trying to create a python script that will loop through all the text files in the specified folder. The text files contain directories to files that will be moved to a different specified folder. When looping through a text file, it takes the file from the file directory on each line of that text file.
The end goal is to have all the files which are referenced in the text file to move into one specified folder (\1855).
import shutil
dst = r"C:/Users/Aydan/Desktop/1855"
with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
for filename in my_folder:
text_file_name = filename.strip()
with open (text_file_name) as my_file:
for filename in my_file:
file_name = filename.strip()
src = r'C:\Users\Aydan\Desktop' + file_name
shutil.move(src, dst)
One text file (1855.txt) contains:
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0002_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0003_1.txt
and another text file (1856.txt) contains:
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0004_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0005_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0006_1.txt
This is the error I get when I run the above script:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Aydan\\Desktop\\RTHPython\\Years'
This script doesn't seem to be moving the files named here to the C:/Users/Aydan/Desktop/1855 destination, even though in the script I'm trying to follow the same logic of iterating through each item in the text file, but applying that logic to a folder instead of inside text file.
Any help to find a solution would be brilliant! If you need any more info about the files just ask.
Thanks!
Aydan.
Since you can't open whole folders with the open method, you can get cycle through every .txt file in that folder like that:
import shutil
import glob
dst = r"C:/Users/Aydan/Desktop/1855"
for filename in glob.glob(r"C:\Users\Aydan\Desktop\RTHPython\Years\*.txt"):
text_file_name = filename.strip()
with open (text_file_name) as my_file:
for filename in my_file:
file_name = filename.strip()
src = r'C:\Users\Aydan\Desktop' + file_name
shutil.move(src, dst)
I have a big list of text files in a folder, and I want to loop over all those file, copy the content of each one and paste in another specific text file that will contain all the looped files content.
This is my beginning of the program:
path = os.listdir(r'C:\Users\ak\Desktop\Nouveau dossier (2)')
final_file = open(r'C:\Users\ak\Desktop\final_file.txt')
for i in path:
f = open(i, 'r')
Then I got this error:
Traceback (most recent call last): File "", line 2, in
f= open('i','r') FileNotFoundError: [Errno 2] No such file or directory: 'i'
What am I doing wrong?
You may need to use join to get the full path. It also looks like in your actual code you have quotes around your variable, i. You should also be using a context manager (with) to save having to remember to close the file. This is how I would do it:
for i in path:
with open(os.path.join(path, i), 'r') as f:
# do something with the file