简体   繁体   中英

Reading a file in Python in Ubuntu

I'm trying to access a .txt file in my root account to open and read in python. My code looks like this:

>>> path = 'root/unpackedFiles/enrollment_fact.txt'
>>> read = open(path,'r')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    read = open(path,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'root/unpackedFiles/enrollment_fact.txt'

I've also tried several variations of this with no such luck. Including:

path = 'unpackedFiles/enrollment_fact.txt' and path = 'enrollment_fact.txt'

Your path is incorrect. Absolute paths need to start with a slash for the root directory. Your path should look like this:

path = '/root/unpackedFiles/enrollment_fact.txt'
>>> path = 'ports.txt'                                          
>>> read = open ( path, 'r')                                    
>>> print(read)                                                 
<_io.TextIOWrapper name='ports.txt' mode='r' encoding='cp1252'> 
>>> exit()                

You have to give either relative path or absolute path.And your code you are missing / before root and so interpreter unable to find the file at given path.

Relative path:

$ ls ports.txt                                                  
ports.txt                                                       

Absolute path:

$ readlink -f ports.txt                                         
/c/Users/rgenupula/ports.txt                                    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM