![](/img/trans.png)
[英]I have a txt file. How can I take dictionary key values and print the line of text they appear in?
[英]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
而不是open
和close
with open(file_name, "r") as f:
#do what you want, close automatically
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.