读取文件内容时no such file or directory: 'star.txt' | python | python 技术论坛-大发黄金版app下载

版本:window10 python3.12.4
需求:读取文件star.txt中内容
问题:显示filenotfounderror: [errno 2] no such file or directory: ‘star.txt’,已做步骤陈列如下,是哪里出了问题,烦指出
file_name = ‘star.txt’
with open (file_name) as file_object:
lines = file_object.readlines()

traceback (most recent call last):
file “”, line 1, in
with open (file_name) as file_object:
filenotfounderror: [errno 2] no such file or directory: ‘star.txt’
补充:已确定拥有读取star.txt权限。
在下萌新,望前辈不吝赐教,谢谢!

jason990420
最佳答案

check if current working directory, os.getcwd(), to confirm if it is same directory for your star.txt.

>>> import os
>>> os.getcwd()
'c:\\software\\python\\lib\\idlelib'

if not, you should add the path to the star.txt file to tell python where to find your file.

file_name = "c:/users/jjy_0/star.txt"
5个月前
(楼主) 4个月前
讨论数量: 5
jason990420

check if current working directory, os.getcwd(), to confirm if it is same directory for your star.txt.

>>> import os
>>> os.getcwd()
'c:\\software\\python\\lib\\idlelib'

if not, you should add the path to the star.txt file to tell python where to find your file.

file_name = "c:/users/jjy_0/star.txt"
5个月前
(楼主) 4个月前

新手建议把这个去掉

5个月前
(楼主) 4个月前

file_name = "c:/users/jjy_0/censuspopdata.xlsx"

import os os.getcwd() 'c:\users\jjy_0\appdata\local\programs\python\python312' file_path = 'c:/users/jjy_0/censuspopdata.xlsx' # 修正了文件扩展名前的空格,并确保大小写正确

try:
with open(file_path, 'rb') as file: # 使用'rb'模式读取二进制文件,如pdf
content = file.read()
print("文件内容已读取。") # 处理content,例如保存到变量或进行其他操作

except filenotfounderror:
print(f"无法找到文件: {file_path}") import openpyxl wb = openpyxl.load_workbook('censuspopdata.xlsx') 最后使用了这个,七拼八凑版的,有前边jason的功劳。(>0<)

4个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图