Python 2:如何在'.text'文档中添加字符串?

时间:2013-07-18 18:23:37

标签: python

我有一个名为'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.

我该怎么做?

3 个答案:

答案 0 :(得分:5)

要使用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!')")

完成后,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')

这将取1到101之间的每个偶数,并以“x is even!”格式将其写入文件。

答案 1 :(得分:3)

以下是您通常用Python编写文件的方式:

with open('new_data.txt', 'a') as output:
    output.write('something')

现在只需在'something'语句中添加您要编写的with,在您的情况下,就是for循环。

答案 2 :(得分:0)

with open('path/to/file', 'a') as outfile:
    for x in range(1,101):
        if x % 2 == 0:
            outfile.write("%s is even\n" %i)