Python 即使文件位于同一文件夹(文本文件)中,程序也无法找到该文件
我正在和学校做一个程序设计项目,其他一切都在进行中;但是,即使文件位于同一文件夹中,程序也无法找到该文件Python 即使文件位于同一文件夹(文本文件)中,程序也无法找到该文件,python,python-3.x,Python,Python 3.x,我正在和学校做一个程序设计项目,其他一切都在进行中;但是,即使文件位于同一文件夹中,程序也无法找到该文件 with open("song_artists.txt") as textfile: lines = [line.split("\n") for line in textfile] ##for item in lines: newItem = str(lines[random.randint(0,2)]) #print(newItem) artist, song, blank =
with open("song_artists.txt") as textfile:
lines = [line.split("\n") for line in textfile]
##for item in lines:
newItem = str(lines[random.randint(0,2)])
#print(newItem)
artist, song, blank = newItem.split(",")
artist = artist[2:len(artist)]
song = song[0:len(song)-1]
print(artist)
for x in range(len(song)):
if song[x] == " ":
print(song[x+1])
上面的代码就是发生错误的地方。错误消息是:文件“W:\year 11\Computer\u Science\Programming\20\u Hour\u Project\Project Code.py”,第61行,在
打开(“song_artists.txt”)作为文本文件:
FileNotFoundError:[Errno 2]没有这样的文件或目录:“song\u artists.txt”这是一个工作目录问题。您可能正在从其他文件夹执行它。要查看从何处运行它,请使用:
import os
print(os.getcwd())
因此,要根据Project code.py
路径查找songs\u artists.txt
,请使用以下命令:
import os
THIS_FILE_PATH = os.path.abspath(__file__)
THIS_FILE_FOLDER_PATH = os.path.dirname(THIS_FILE_PATH)
SONG_ARTIST_FILE_PATH = os.path.join(THIS_FILE_FOLDER_PATH, 'song_artists.txt')
with open(SONG_ARTIST_FILE_PATH) as textfile:
lines = [line.split("\n") for line in textfile]
…您可能正在从“home”目录运行python文件,您需要将完整路径添加到文本文件或将终端文件夹更改为20小时项目添加
导入操作系统;将(os.getcwd())
打印到开头以查看您的位置。使用“打开”(r“W:\year 11\Computer\u Science\Programming\20\u Hour\u Project\song\u Artisters.txt)````