Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 即使文件位于同一文件夹(文本文件)中,程序也无法找到该文件_Python_Python 3.x - Fatal编程技术网

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)````