pycharm不会在我的Macbook上读取txt文件吗?

时间:2018-11-28 21:01:19

标签: python

我有一个代码需要对文本文件中的比赛时间进行排序,这是我到目前为止的结果,

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'

在无法读取文本文件的地方发生了什么?我的桌面上有文本文件。

1 个答案:

答案 0 :(得分:0)

您的文件正在"/Users/jess/Library/Preferences/PyCharmEdu4.0/scratches/scratch.py"上运行,但是您说该文件在桌面上。您需要将absolute reference传递到桌面文件。

我建议将文件移动到"/Users/jess/Library/Preferences/PyCharmEdu4.0/scratches/。然后您可以在脚本中使用相对引用找到它,即

with open("Race_Results_Sample.txt", "r")as myList:

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