即使文件位于同一文件夹(文本文件)中,程序也无法找到文件

时间:2019-11-21 12:29:35

标签: python python-3.x

 The image is the way the files are stored.我正在与学校进行编程项目,其他所有工作都在进行;但是,该程序即使在同一文件夹中也找不到该文件。

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:[错误2]没有这样的文件或目录:'song_artists.txt'

1 个答案:

答案 0 :(得分:2)

这是一个工作目录问题。您可能正在其他文件夹中执行它。要查看使用它的位置,请执行以下操作:

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]

...