0

I've been working on this bit of code trying to open multiple files in a directory. The directory contains 10 text files. I want to open each of the files, do some stuff to it (namely remove stop words) and output the transformed text into a new file in a different directory. However, I have this problem:

FileNotFoundError: [Errno 2] No such file or directory: '1980'

The file definitely exists in the directory and I have been giving the absolute path. I have looked at the current working directory before opening the file and it does not return the absolute path I gave it, rather the directory where this project is located. Any help in getting the code to open the necessary files and write the result to the output file would be greatly appreciated! Here is my code:

path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(path):
    for file in files:
        print(os.getcwd())
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            x = ''
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open('out', 'w') as output_file:
                output_file.write((' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords))))
Fordo
  • 61
  • 1
  • 9
  • Try to change the name of the directory to something like an alpha name not numbers, then execute again, I guess the problem is it. – Elder Santos Feb 27 '19 at 22:12
  • What do you mean by 'alpha name not numbers'? – Fordo Feb 27 '19 at 22:15
  • By the error you put, the directory is called '1980' (FileNotFoundError: [Errno 2] No such file or directory: '1980'), change the name of the directory to something like 'nineteen_eighty' and try to run it again – Elder Santos Feb 27 '19 at 22:21
  • No that doesnt seem to work. The error now says: (FileNotFoundError: [Errno 2] No such file or directory: 'nineteen_eighty') – Fordo Feb 28 '19 at 00:09

2 Answers2

0

Are you on Windows? Whenever I do absolute paths on Windows I need to use backslash() for pathing instead of forward slash (/).

Adam Roman
  • 97
  • 5
  • No, unfortunatley, that doesn't work either. I get this error: path = 'C:\Users\User\Desktop\mini_mouse' ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape – Fordo Feb 28 '19 at 09:40
0

The problem with your code is the fact '1980' is not the full path to the file it is just a string. You should append the rest of the path like below, using for example the path.join:

with open(os.path.join(path, file), 'r') as f, open(os.path.join(path, 'NLTK-stop-word-list'), 'r') as f2:

Then Python will be able to find the file and open it in read mode.

Elder Santos
  • 309
  • 2
  • 11