2013-07-18 70 views
-3

我有一個'.txt'文件叫做'new_data.txt'。現在它是空的。但我有一個'如果'聲明'爲'循環,如果'x'甚至與否。如果真的我想(x +'是偶數!')將被添加到我的'new_data.txt'文件。Python 2:我如何添加一個字符串到'.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. 

我該怎麼做?

+0

爲什麼被標記爲[csv]? – geoffspear

+0

刷新你的文件處理技巧。這應該是一件容易的事情。 :) –

+0

從頭開始的''''''模式,用於追加到文件末尾的''''模式。 – 2rs2ts

回答

3

這裏是你如何寫,通常在Python中的文件:

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

現在只需添加'something'要在with語句中寫,你的情況,那就是for循環。

+2

這不會「添加」到文件。相反,它會覆蓋文件的預先存在的內容。在打開 – inspectorG4dget

+0

時使用「a」標誌以寫入模式打開文件將清除文件中的所有內容。它不應該是追加模式嗎? – iCodez

+0

夥計們:問題有點不清楚,OP希望向某個空文件「添加」某些內容,但這可能是因爲他只是想「寫」它。我編輯了我的答案,以防萬一。 –

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是偶數!」。

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) 
相關問題