簡體   English   中英

在Ubuntu中用Python讀取文件

[英]Reading a file in Python in Ubuntu

我試圖在我的根帳戶中訪問.txt文件以打開並讀取python。 我的代碼如下所示:

>>> 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'

我也嘗試過幾種變體,但沒有運氣。 包含:

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

您的路徑不正確。 根目錄的絕對路徑必須以斜杠開頭。 您的路徑應如下所示:

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()                

您必須提供相對路徑或絕對路徑,並且您的代碼缺少/root之前,因此解釋器無法在給定路徑下找到文件。

相對路徑:

$ ls ports.txt                                                  
ports.txt                                                       

絕對路徑:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM