0

I have looked at How to open a list of files in Python This problem similar but not covered.

path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []

for f in files:
    fileNames.append(f)
    
for fileName in fileNames: 
    pathFileName = path + fileName  
    print(f"This is the path: {pathFileName}") 
    fin = open(pathFileName, 'rt')

    texts = []

    with open(fileName) as file_in:
        # read file text lines into an array    
        for text in file_in:
            texts.append(text)

        for text in texts:
            print(text)

The file aaaatest.txt is in C:\test\test5 The output is:

This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'

So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:

This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'

The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again. Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?

Dave
  • 687
  • 7
  • 15
  • 1
    You're opening a file twice on each iteration of the loop: once with the full pathname, that you don't do anything further with, and once with just the filename, which is only going to be looked for in the CWD and most likely fail. – jasonharper Dec 17 '22 at 00:51
  • Thank you. Major oversight on my part. Yup. When I commented out `with open` & `read file` all is good – Dave Dec 17 '22 at 01:06

0 Answers0