2017-10-20 356 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