簡體   English   中英

如果我有一個字典,其中行的鍵和內容是文本,如何輕松地將行寫入文本文件?

[英]How do I write lines to a text file easily if I have a dictionary with the key of the line and contents being the text?

如果有更智能/更簡單的方法可以做到這一點,我會很高興知道。 我的文件處理知識非常基礎,所以我現在處於未知領域。

有問題的代碼:

fileBin = open("HarryPotterBooks.txt", "r")
fileKeys = open("HarryPotterBooks.txt", "r")

binValues = list(list(map(lambda x: bin(ord(x)), line)) for line in fileBin)

keys = list(
    x for x in range(len([line.strip("\n") for line in fileKeys if line != "\n"]))
)

res = dict(zip(keys, binValues))

fileBin.close()
fileKeys.close()


newFile = open("BinaryConverted.txt", "w")

# Writing to the file

最好使用with open而不是openclose

with open(file_name, "r") as f:
    #do what you want, close automatically

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM