Importing File using open()

asked 2024-05-07 00:56:54 +0200

Taha gravatar image

updated 2024-05-07 07:36:23 +0200

FrédéricC gravatar image

Hello, I am trying to use the following code to access a file that is not in the same folder as my .ipynb note book. However, it is giving me an error message.


  alldata = open("C:/Users/tahah/Desktop/hihi.txt", "r")    


  FileNotFoundError                         Traceback (most recent call last)
  /tmp/ipykernel_1888/ in <module>
  ----> 1 alldata = open("C:/Users/tahah/Desktop/hihi.txt", "r")
        2 print(
  FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/tahah/Desktop/hihi.txt'

I have no idea how to fix this. Is anyone able to help? I'm just testing a txt file, but my goal is to be able to open a csv file. (I wanted to mention that in case it changes anything.)

Thanks in advance!

edit retag flag offensive close merge delete


Maybe using instead

from pathlib import Path

data = Path("C:\Users\etc").open()

Beware of the slash versus backslash problem also.

FrédéricC gravatar imageFrédéricC ( 2024-05-07 07:39:19 +0200 )edit

Note that


is useful to know the current directory.

FrédéricC gravatar imageFrédéricC ( 2024-05-07 08:59:39 +0200 )edit

Shouldn't it be a raw string - r"C:\Users\etc" ?

Max Alekseyev gravatar imageMax Alekseyev ( 2024-05-09 16:59:57 +0200 )edit