python - 使用python打开txt文件时出现FileNotFoundError

标签 python file error-handling

我正在尝试使用以下代码打开一个 txt 文件进行阅读:-

type_comments = [] #Declare an empty list
with open ('society6comments.txt', 'rt') as in_file:  #Open file for reading of text data.
 for line in in_file: #For each line of text store in a string variable named "line", and
   type_comments.append(line.rstrip('\n'))  #add that line to our list of lines.

错误:-

Error  - Traceback (most recent call last):
  File "c:/Users/sultan/python/society6/society6_promotion.py", line 6, in <module>
    with open ('society6comments.txt', 'rt') as in_file:
FileNotFoundError: [Errno 2] No such file or directory: 'society6comments.txt'

我的脚本在同一目录中已经有一个名为“society6comments.txt”的文件,那么为什么它显示错误?

enter image description here

最佳答案

文本文件与程序位于同一目录中这一事实并不会使该目录成为当前工作目录。将文件的完整路径放入 open() 调用中。

关于python - 使用python打开txt文件时出现FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52407669/

相关文章:

python - 为什么压缩会输出更大的 zip 文件?

c++ - 大整数被误读/误写入二进制文件

c# - 数据验证和异常处理之间有什么区别?

python - 如何使用 Python 在 WordNet 中生成形容词的反义词列表

python - nginx + uwsgi 用于使用多个端口的多个站点

python - 操作系统错误 : [Errno 8] Exec format error selenium

javascript - PhoneGap/Cordova for android 文件插件错误代码 1

scala - (Scala)错误处理

error-handling - 我可以将有关未初始化变量的注释升级为错误吗?

python - 需要帮助从 csv excel 文件创建字典