简体   繁体   English

在Ubuntu中用Python读取文件

[英]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. 我试图在我的根帐户中访问.txt文件以打开并读取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' path = 'unpackedFiles/enrollment_fact.txt'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. 您必须提供相对路径或绝对路径,并且您的代码缺少/root之前,因此解释器无法在给定路径下找到文件。

Relative path: 相对路径:

$ ls ports.txt                                                  
ports.txt                                                       

Absolute path: 绝对路径:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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