1

I have both txt and python file in the same folder and I am trying this :

f =open('sample.txt')
data = f.read()
print(data)
f.close()

but still, I am facing the error.

I don't want to write the full path of the file is there any way to fix this error.

The Image of folder

Mark
  • 4,249
  • 1
  • 18
  • 27
  • 3
    Add the following code `import os; print(os.getcwd())` and see where you program is running from. – Tom Dalton Jun 03 '21 at 14:56
  • 3
    try `import os; print(os.listdir())` and check files. – Corralien Jun 03 '21 at 14:56
  • As per Thomas John, consider that your file name is wrong. Can you modify your windows settings to show you the extensions, or do a 'dir' from the command prompt. Are you certain that you are running the program from that directory? Maybe you can add a little temporary code in the beginning of your short program to list the files in the directory. All in all , we are not certain of the file name or the current directory when you run your program. – Mark Jun 03 '21 at 14:59
  • I have tried this in Atom code editor there it is working. –  Jun 03 '21 at 15:33

4 Answers4

1

You need to execute your python instance in that folder, your python runtime will only find files on where it is running.

For example you have your files_01.py on the Files folder, you need to open a CMD and go to that folder and execute your python file from there, or if your are using VSCode you need to open the integrated terminal, move to the Files folder and execute the python command from there, that will make your python runtime to find the file sample.txt on the root of the executing environment

Ronald Petit
  • 474
  • 1
  • 4
  • 23
-1

Remove the file extension .txt and try. Your extension is creating the file not found error.

f = open('sample')

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Thomas John
  • 2,138
  • 2
  • 22
  • 38
  • 2
    I believe his windows settings are set to hide extensions - so we don't see that the file is really called sample.txt (or something else). But there is likely an extension there - so I think you are on the right track - clearly he's got the file name wrong. – Mark Jun 03 '21 at 14:57
-1

Try this instead:

f = open("./sample.txt", "r")

If you know some basics about terminal and directories, you would know what ./ means but in layman terms, it basically indicates that the file is in the current directory being worked in.

This can also be caused if the folder opened in VSCode is a workspace. If assuming your 'Development' folder is a workspace then try this:

f = open("./Visual Studio Code (Projects)/Python/sample.txt", "r")
-1

As Thomas explained earlier. Try removing txt extension from the file name and try again. Also, I would use the with keyword for file objects.

with open(filename,'rt') as f:
    file_data = f.read()

This way I don't have to worry about writing f.close()

Paul
  • 35
  • 5