0

I'm working on a sentiment analysis program for an NLP class. I've imported a folder with a lot of different files and my goal is to merge all of the files text together to analyze it as one big pool of text. So far I've been able to import all of the files using:

path = "noblespeeches" 
nobel_speeches = os.listdir(path)

files = sorted([file for file in nobel_speeches if file.endswith('.txt')])

...where "nobelspeeches" is the path to the appropriate file on my computer. I've tested this part and it seems to work fine. I'm having trouble creating a function to read the files so I can merge all of the text together.

def read_file(file_name):
  with open(file_name, 'r+', encoding='utf-8') as file:
    file_text = file.read()
  return file_text

This function is what I've been working with, and I cannot seem to get it to work for the life of me. I'm sure the answer is quite simple, but I'm fairly new to Python and very new to NLP. I've been researching different possible solutions to no avail.

The error code is: FileNotFoundError: [Errno 2] No such file or directory:

The machine is producing an error that states that the first file in my folder doesn't exist even though it will acknowledge the file in the earlier code.

karel
  • 5,489
  • 46
  • 45
  • 50
  • Welcome to Stack Overflow. Please read [ask], then [edit] your question to include the _full_ traceback. Also, please review [How to Debug Small Programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – ChrisGPT was on strike Aug 12 '21 at 02:14
  • In function `read_file` you are passing `file_name`. this file_name need to be absolute path(i.e complete path) or python script should in the same directory `noblespeeches`. for debug you can put `print(file_name)` in your function. – simpleApp Aug 12 '21 at 02:38

1 Answers1

0

Chang this

files = sorted([os.path.join(path, file) for file in nobel_speeches if file.endswith('.txt')])
Trock
  • 546
  • 2
  • 13
  • Thank you! This did the trick. If you have a minute, would you mind explaining the logic behind this change? – Eloragh Espie Aug 12 '21 at 02:54
  • the value of file is like "1.txt". Missing directory "noblespeeches". The file name you need should be the full path: "noblespeeches/1.txt". So use os.path.join(path, file) to splice dir and filename. – Trock Aug 12 '21 at 02:59