2017-10-20 358 views
0

我有兩個部分創建的程序。使用Python3寫入ASCII格式的文件,而不是UTF8

第一個以這種格式在文件名中間以整數形式複製文本文件。

file = "Filename" + "str(int)" + ".txt" 

用戶可以創建他們想要的文件副本。

程序的第二部分是我遇到的問題。文件最底部有一個整數,與文件名中的整數對應。第一部分完成後,我以"r+"讀/寫格式一次打開一個文件。所以我可以file.seek(1000)大約整數在文件中的位置。

現在我認爲下一部分應該很容易。我只需要在這裏將str(int)寫入文件即可。但這並不容易。在家裏的Linux中,它工作得很好,但在Windows上工作很困難。我使用Unicode UTF-8將file.seek(1000)之後必須要做的事情寫入文件。我用程序其餘部分的這段代碼完成了這個任務。我將記錄它,以便能夠理解正在發生的事情。我不想用Unicode編寫它,而是希望能夠用良好的舊的普通英文ASCII字符來編寫它。最終,這個程序將被擴展爲在每個文件的底部包含更多的數據。不得不用Unicode編寫數據會讓事情變得非常困難。如果我只是寫入數據而不把它轉換成Unicode,這就是結果。這個字符串應該說是#2 =1534,而不是它說的#2 =ㄠ㌵433.

如果有人能告訴我我做錯了什麼,那將會很棒。我希望僅使用file.write('1534')之類的數據將數據寫入文件,而不必使用Unicode UTF-8。

while a1 < d1 : 
    file = "file" + str(a1) + ".par" 
    f = open(file, "r+") 
    f.seek(1011) 
    data = f.read() #reads the data from that point in the file into a variable. 
    numList= list(str(a1)) # "a1" is the integer in the file name. I had to turn the integer into a list to accomplish the next task. 
    replaceData = '\x00' + numList[0] + '\x00' + numList[1] + '\x00' + numList[2] + '\x00' + numList[3] + '\x00' #This line turns the integer into Utf 8 Unicode. I am by no means a Unicode expert. 
    currentData = data #probably didn't need to be done now that I'm looking at this. 
    data = data.replace(currentData, replaceData) #replaces the Utf 8 string in the "data" variable with the new Utf 8 string in "replaceData." 
    f.seek(1011) # Return to where I need to be in the file to write the data. 
    f.write(data) # Write the new Unicode data to the file 
    f.close() #close the file 
    f.close() #make sure the file is closed (sometimes it seems that this fails in Windows.) 
    a1 += 1 #advances the integer, and then return to the top of the loop 
+0

這不是UTF-8。它看起來更像UTF-16BE。 –

+0

好吧,我不確定我自己。感謝您的更正。我不熟悉Unicode。我基本上只是用與舊的格式相同的格式創建新的字符串,但使用不同的數字。 – CigEmacs

回答

1

這是用ASCII寫入文件的一個例子。您需要以字節模式打開文件,並且使用字符串的.encode方法是獲取所需最終結果的便捷方式。

s = '12345' 
ascii = s.encode('ascii') 
with open('somefile', 'wb') as f: 
    f.write(ascii) 

如果文件已經存在,你很明顯可以在rb +(讀寫字節模式)中打開你的情況。

with open('somefile', 'rb+') as f: 
    existing = f.read() 
    f.write(b'ascii without encoding!') 

也可以只通過文字串用B前綴,它們將與ASCII編碼爲示出在第二示例。

+0

謝謝。我會嘗試。如果我想以讀/寫方式打開文件,它會是「打開('somefile','r + b')」正確嗎? – CigEmacs

+0

@CigEmacs檢查我的編輯。很高興我能幫上忙。 – Evan

+0

@CigEmacs如果我的答案是解決您的問題,如果您可以將其標記爲已接受的答案,我將不勝感激。 – Evan