【发布时间】:2015-06-14 06:04:09
【问题描述】:
我在这个网站上搜索过类似的问题,但没有找到任何有效的解决方案,因此,这个问题。
我正在编写一个 Python 3.4 程序,其中有一个函数 export,它基本上将数据附加到文本文件中。
该函数检查以确保存在适当的文件,如果没有,则创建一个,然后获取文件的内容,添加附录并覆盖文件。
Python 在for line in file: 处抛出错误另外,再次运行该程序时,一旦创建了文本文件,就不会发生此错误。
这是函数:
def export(addendum, user):
filename = user + '.txt'
try:
file = open(filename, 'r')
except OSError:
file = open(filename, 'w')
export(addendum, user)
file_contents = ''
print('What day is it? (1-5)')
day = input()
day = int(day)
if day >= 1 and day <= 5:
for line in file:
file_contents += line
file = open(filename, 'w')
new_file = file_contents + '\n' + addendum
file.write(new_file)
file.close()
else:
print('Invalid weekday number...')
sys.exit()
【问题讨论】:
标签: python macos python-3.x file io