[英]Saving data into a text file
def ConvertFile():
FileNameIn = 'Hexdata.dat'
HexFile = open(FileNameIn, 'r')
for Line in HexFile:
print (Line)
print (Binary(Line))
HexFile.close()
到目前為止,我已經有了,當程序運行時,它將文件中的十六進制數轉換為二進制數。 這是在一個名為 Hexdata.dat 的文件中
我想要做的是將二進制 output 保存到一個名為 Binarydata.dat 的文件中
我將如何在代碼中處理這個問題? 請注意,我是 Python 的新手,並沒有正確介紹這一點。 我嘗試了不同的代碼,但都沒有成功,實際上,它們都是猜測。
我不是要你幫我解決問題,而是問我如何將程序的 output 保存到一個新的文本文件中。
你已經完成了大部分工作。 您已經知道如何打開文件進行閱讀:
HexFile = open(FileNameIn, 'r')
那里的'r'
意思是“開放閱讀”。 如果您查看open
function 的文檔,您將看到用w
替換r
將打開一個文件進行寫入:
OutputFile = open(FileNameOut, 'w')
然后你可以像這樣發送 output 給它:
print >>OutputFile, "Something to print"
或者對文件object使用write
方法:
OutputFile.write("Something to print\n")
您當前正在以讀取模式打開文件,因此為了寫入文件,您需要以('w')
的緩沖模式打開文件。 引用自: http://docs.python.org 。 您可以通過將'r'
替換為'w'
來輕松做到這一點。
'w' for writing (truncating the file if it already exists
有關更多參考,請參閱open(name[, mode[, buffering]])
# the file name
FileNameIn = 'Hexdata.dat'
# create a file object: open it with "write" mode
HexFile = open(FileNameIn,"w")
for line in HexFile:
HexFile.write(Binary(line))
HexFile.close()
您是否嘗試過使用 open('Binarydata.dat', 'w') 寫入文件? 有很多方法可以寫入文件,其中大部分可以在這里找到: http://docs.python.org/tutorial/inputoutput.html
閱讀open function (以寫入模式打開文件)和File Objects (將信息寫入打開的文件)的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.