首页 > 解决方案 > 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'

无法读取文本文件的原因是什么?我的桌面上有文本文件。

标签: python

解决方案


您的文件正在运行,"/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:

您还应该确保从该目录执行脚本。


推荐阅读