我有一个名为'new_data.txt'的'.txt'文档.现在它是空的.但是我在'for'循环中有一个'if'语句,如果'x'偶数与否则会出现.如果我想要(x +'是偶数!')添加到我的'new_data.txt'文档中.
for x in range(1,101):
if x % 2 == 0:
# and here i want to put something that will add: x + ' is even!' to my 'new_data.txt' document.
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
要使用Python写入文件,请使用with语句和open内置函数:
# The "a" means to open the file in append mode. Use a "w" to open it in write mode.
# Warning though: opening a file in write mode will erase everything in the file.
with open("/path/to/file", "a") as f:
f.write("(x + ' is even!')")
Run Code Online (Sandbox Code Playgroud)
完成后,该with语句负责关闭文件.
此外,在您的脚本中,您可以简化它并执行:
with open('/path/to/file','a') as file:
for x in [y for y in range(1,101) if not y%2]:
file.write(str(x)+' is even!\n')
Run Code Online (Sandbox Code Playgroud)
这将取1到101之间的每个偶数,并以"x is even!"格式将其写入文件.
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |