我正在尝试打开一个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',为什么它显示错误?
答案 0 :(得分:2)
该文本文件与您的程序位于同一目录中,这一事实并不会使该目录成为当前工作目录。在您的java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
调用中放入文件的完整路径。
答案 1 :(得分:0)
您可以使用os.path.dirname(__file__)
获取脚本的目录名称,然后加入所需的文件名:
import os
with open (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'society6comments.txt'), 'rt') as in_file: