python - 即使文件位于同一文件夹(文本文件)中,程序也无法找到文件
问题描述
我正在和学校一起做一个编程项目,其他一切都在工作;但是,即使该文件位于同一文件夹中,程序也无法找到该文件。
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'
解决方案
这是一个工作目录问题。您可能正在从不同的文件夹执行它。要查看您在哪里运行它,请使用:
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]
...
推荐阅读
- google-apps-script - 为什么它不能从活动范围中找到列?
- python - 无法使用内置绘图仪绘制熊猫数据框
- python - 为什么加载数据集“.load_data()”时python会失败
- karate - 在我的端到端自动化的大部分部分中寻找使用空手道框架的解决方案
- javascript - 在服务器和浏览器上使用 Macchiato 框架的苹果酒
- python - 只需键入 python nameofthescript.py 在 Windows 10 cmd 上运行 python 脚本
- .net-core - dotnet core 3 未在 IIS 上读取 X-FORWARDED-HOST
- c# - 为什么 ExpandoObject 比 Dictionary 慢得多?
- java - 如何设置 IntelliJ IDEA 以便多模块 Maven 项目可以存储为单独的 Git 存储库但“导入”到 IntelliJ 项目中
- node.js - 尝试连接到 node.js 服务器(未托管在 localhost 上)时如何修复 ERR_CERT_COMMON_NAME_INVALID?