1

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.

Daniyal Warraich
  • 446
  • 3
  • 13
  • 2
    What do you mean by "this will not work?" Do you see any errors? What do you get printed to the screen? How are you running the Python code? Maybe Python doesn't have permissions to access the file. – gen_Eric Feb 01 '21 at 18:52
  • 1
    "Even this will not work" - what do you mean ? Are there errors ? Does i print nothing ? Please add details to your post. – TheEagle Feb 01 '21 at 18:53
  • 1
    How do you run the Python script? – 9769953 Feb 01 '21 at 18:54
  • 1
    @RocketHazmat i duplicated your comment without knowing .... – TheEagle Feb 01 '21 at 18:54
  • 1
    after i put the 'python filename.py' in the command line, it will do nothing. No errors are produced, and it just does absolutely nothing. I have no better words to describe nothing. – Daniyal Warraich Feb 01 '21 at 18:54
  • @Programmer that's fine :-) We all want to help here :-D – gen_Eric Feb 01 '21 at 18:54
  • 1
    Are you with your cmd in the directory where you textfile is? Avoid using `file` as a variable. Is this all your code or you wrapped it into the function? – Leemosh Feb 01 '21 at 18:56
  • @JohnDoe could you post a screenshot of your screen directly after running the program ? – TheEagle Feb 01 '21 at 18:56
  • 1
    Do you by chance have the [Python app store stubs](https://stackoverflow.com/a/57168165/2378643) installed? They can act like this when passed command lines. – Anon Coward Feb 01 '21 at 18:56
  • Oh, and I am using Windows 10, Python 3.9.1, and I run the script in the command prompt app. Before, it would work perfectly – Daniyal Warraich Feb 01 '21 at 18:57
  • @JohnDoe Try wrapping this code in a `try`/`except` block. Like `try: open(...) except Exception as e: print(e)`. – gen_Eric Feb 01 '21 at 18:57
  • 3
    add `print("Hello !")` to the top of your script, and see if that gets printed. – TheEagle Feb 01 '21 at 18:57
  • Keep some print statements and check whether they're working or not – Ashok Feb 01 '21 at 18:58
  • ok, i will do that, and i will screenshot it – Daniyal Warraich Feb 01 '21 at 18:59

2 Answers2

2

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.

Daniyal Warraich
  • 446
  • 3
  • 13
1

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)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103