python - pycharm 不会在我的 macbook 上读取 txt 文件?
问题描述
我有一个代码需要从文本文件中对比赛时间进行排序,这就是我目前所拥有的,
def get_sec(time_str):
h, m = time_str.split(':')
return int(h) * 3600 + int(m) * 60
with open("Race_Results_Sample.txt", "r")as myList:
myList = myList.read()
myList = [l.split(",") for l in myList.splitlines()]
myList = sorted(myList, key=lambda kv: kv[1])
for line in myList:
num, last, org, time = line
place = []
place.append(time)
placenum = enumerate(sorted(place))
print(place, placenum)
for rank, value in enumerate(sorted(place)):
print(rank, value)
for line in myList:
num, last, org, time = line
new_time = get_sec(time)
mile = round((((new_time/ 3.10686)/60)/60), 3)
mile = str(mile)
print ('{:<20s}{:<5s}{:<5s}{:<7s}{:<10s}'.format(last, num, org,
time, mile))
当试图让代码运行时,我收到以下消息:
Traceback (most recent call last):
File
"/Users/jess/Library/Preferences/PyCharmEdu4.0/scratches/scratch.py",
line 5, in <module>
with open("Race_Results_Sample.txt", "r")as myList:
IOError: [Errno 2] No such file or directory: 'Race_Results_Sample.txt'
无法读取文本文件的原因是什么?我的桌面上有文本文件。
解决方案
您的文件正在运行,"/Users/jess/Library/Preferences/PyCharmEdu4.0/scratches/scratch.py"
但您说该文件在您的桌面上。您需要传递对桌面文件的绝对引用。
我建议将文件移动到"/Users/jess/Library/Preferences/PyCharmEdu4.0/scratches/
. 然后你可以用你在脚本中使用的相对参考找到它,即
with open("Race_Results_Sample.txt", "r")as myList:
您还应该确保从该目录执行脚本。
推荐阅读
- python - 如何解决 IDA Python 中的 1491 错误?
- typescript - if/else 分支没有缩小条件类型
- matlab - 如何模拟多元 t 分布后的随机点?
- python - 使用 flow_from_dataframe 方法时出现“列表索引超出范围”错误
- c++ - 如何正确地将 ATL 包含到 Embarcadero 项目中
- javascript - 我想根据设备显示不同的图像
- openssl - Openssl 验证 -CRLFile 与 -crl_download?
- javascript - onclick 事件应该转到 IP 地址然后注销,但它只显示按下按钮的 IP
- python - Python - 来自 csv 文件的 SQLITE db 更新条目
- snowflake-cloud-data-platform - 是否可以创建 SQL 查询模板?