首页 > 解决方案 > 即使文件位于同一文件夹(文本文件)中,程序也无法找到文件

问题描述

图像是文件的存储方式。我正在和学校一起做一个编程项目,其他一切都在工作;但是,即使该文件位于同一文件夹中,程序也无法找到该文件。

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_Science\Programming\20_Hour_Project\Project Code.py”,第 61 行,以 open("song_artists.txt") 作为文本文件:FileNotFoundError: [Errno 2] No such file或目录:'song_artists.txt'

标签: pythonpython-3.x

解决方案


这是一个工作目录问题。您可能正在从不同的文件夹执行它。要查看您在哪里运行它,请使用:

import os
print(os.getcwd())

因此,要songs_artists.txt根据Project Code.py路径进行定位,请使用以下命令:

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]

...


推荐阅读