Search code examples
pythondirectoryedicontextmanager

Iterating and modifying files in a directory


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?


Solution

  • 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