Python file is not reading contents of a text file

Question:

My Python file, which is just a very small file, will not read the contents of a .txt file in the same folder as the python file. The (very simple) code is below:

file = open("contents.txt", "r")

print(file.read())

file.close()

Even this will not work! The contents.txt file contains:

random data that the python file should read

Can anyone help?

P.S. No errors are produced, and the command prompt app just moves on.

Asked By: Daniyal Warraich

||

Answers:

Never mind, it works. The file was located in a different folder, and once i brought it to the folder with the python file, it worked.

Answered By: Daniyal Warraich

first method:- you can simply write folder name before the file name.

second method:- use the below code:-

with open("FolderName/fileName", "r") as f:

  a = f.read()

  print(a)
Answered By: Yasir Mohiuddin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.