在Python中打开'.txt'文件

伍迪

答案已经确定

The problem was not listing the entire file listing (i.e. DRIVE1\DRIVE2\...\fileName.txt).
Also, note that the backslashes must be turned into forwardslashes in order for
Python to read it (backslashes are outside of the unicode listing).
Thus, using: addy = 'C:/Users/Tanner/Desktop/Python/newfile.txt'
      returns the desired results.

同时,因为我已经有玩过这是一个Python的,和我最近的类,我们都需要做出一个BFS搜索,做了文字解谜爱丽丝梦游仙境作者创建。我只是在说明这一点,因为算法是我已经完成的作业。换句话说,我的问题不适用于我的家庭作业问题的答案。

有了这种方式,我需要有关如何在Python中打开,编辑,读取,创建某种形式的文本文件的帮助。我真正的问题是将.txt文件中包含的单词列表放入Dictionary 但我宁愿自己做。因此,我剩下如何处理文本文件了。

注意

 I am running v3.3. 
 All documentation that I have found while searching how to solve this simple problem
      is in regards to 2.7 or older.

我尝试使用:

>>> import sys from argv
>>> script, filename = argv
    Traceback (most recent call last):
    File "<pyshell#15>", line 1, in <module>
       script, filename = argv
    ValueError: need more than 1 value to unpack

我也尝试使用:

>>> f = open(newfile.txt, 'r')

但是再次,我得到这个错误:

 File "<pyshell#8>", line 1, in <module>
        f = open (filename, 'r')
 FileNotFoundError: [Errno 2] No such file or directory: 'newfile.txt'

但是,我肯定这个文件确实存在。所有这些都说明了,我不确定这是目录问题,理解问题还是什么……也就是说,任何事情都会有所帮助!

伊塞捷夫

首先,如果要检索作为脚本的第一个参数传递的文件名,请使用如下代码:

import sys
if len(sys.argv) > 2:
    filename = sys.argv[1]
else:
    # set a default filename or print an error

其次,该错误明确表明该脚本找不到该文件newfile.txt因此它不在当前目录中,您无权读取它,等等。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章