2017-09-15 40 views
1

我一直在閱讀關於編碼和python I/O文檔,但由於我對編程有點新不夠了解。我只是想讀一個文本文件,然後將每行保存到另一個文本文件。但這些行中的一部分是日文字符,雖然打印時它們正確顯示在Python IDE中,但文件中的結果文本只是空的。這就是我想要做的事:儘管被寫入,文件仍然爲空。

filename = 'test.txt' # File with the japanese characters 
filename2 = 'test2.txt' 

text = open(filename,'rb') # I've tried opening it as 'utf-8' too 
text2 = open(filename2,'w',encoding='utf-8') # Output file 

for line in text: 
    new_line = line.decode() # From bytes to utf-8   
    print(new_line) # Just to check 
    text2.write(new_line) 

# Checking if file was written 
text3 = open(filename2,'r',encoding='utf-8') 

for line2 in text3: 
    print(line2 + 'something') 

這段代碼只是打印從輸入文件中的行,但使用的最後一位打印什麼在輸出文件時,不打印輸出。我在Linux上試用這個,輸出文件test2.txt,它只是空的,甚至沒有英文的行。如果我嘗試在Windows上運行此操作,那麼在使用.write()時,我會收到有關charmap無法識別該字符或某些內容的錯誤。如果我刪除日語中的所有行,這工作得很好。我也試着用utf-8編碼打開輸入文件(它已經以這種方式保存,但以防萬一)而不是字節,但它是相同的結果。

以防萬一,這是日本行之一:

▣世界から解放され▣

希望你能幫助我:)

編輯:我使用Python 3.5.2。

+1

你永遠不會關閉,刷新文件。 –

+1

試試這個:https://stackoverflow.com/questions/6048085/writing-unicode-text-to-a-text-file – minterm

+0

你是如何檢查文件是空的旁邊的python代碼?因爲當我運行你的示例時,它會生成一個文件,其中包含utf-8編碼的字符。 – pvg

回答

1

編碼沒問題,看不到上次打印結果的問題是您已經打開文件test2.txt進行寫入。直到您明確關閉流text2,您將無法從另一個流中的文件讀取數據。所以:

# close write stream 
text2.close() 
# now you can open the file again to read from it 
text3 = open(filename2,'r',encoding='utf-8') 

測試它在Linux和OSX產量:

$ echo "▣世界から解放され▣" > test.txt 
$ python3.5 script.py 
▣世界から解放され▣ 

▣世界から解放され▣ 
something 
0

你必須關閉文件,所有的內容被寫入。最好,使用with -statement:

filename = 'test.txt' # File with the japanese characters 
filename2 = 'test2.txt' 

with open(filename,'r',encoding='utf-8') as text: 
    with open(filename2,'w',encoding='utf-8') as text2: 
     for line in text: 
      text2.write(line) 
相關問題