如何将文件读取为 .dat 并将其写入为 .txt

How to read file as .dat and write it as a .txt

所以我做了一个东西,它从 .dat 文件读取数据并将其保存为列表,然后获取该列表并将其写入 .txt 文件(基本上是 .dat 到 .txt 的转换器).但是,每当我 运行 它并生成文件时,它都是一个 .txt 文件,但它包含 .dat 数据。排除故障后写入 .dat 文件的变量是正常清晰的 .txt 不是奇怪的 .dat 数据...

这是我的代码(请不要吐槽我是新手,我知道它很糟糕并且有很多错误,请让我成为 xD):

#import dependencies
import sys
import pickle
import time

#define constants and get file path
data = []
index = 0
path = input("Absolute file path:\n")

#checks if last character is a space (common in copy+pasting) and removes it if there is a space
if path.endswith(' '):
    path = path[:-1]


#load the .dat file into a list names bits
bits = pickle.load(open(path, "rb"))

with open(path, 'rb') as fp:
    bits = pickle.load(fp)

#convert the data from bits into a new list called data
while index < len(bits):
    print("Decoding....\n")
    storage = bits[index]
    print("Decoding....\n")
    str(storage)
    print("Decoding....\n")
    data.append(storage)
    print("Decoding....\n")
    index += 1
    print("Decoding....\n")
    time.sleep(0.1)

#removes the .dat of the file
split = path[:-4]

#creates the new txt file with _converted.txt added to the end
with open(f"{split}_convert.txt", "wb") as fp:
    pickle.dump(data, fp)

#tells the user where the file has been created
close_file = str(split)+"_convert.txt"
print(f"\nA decoded txt file has been created. Run this command to open it: cd {close_file}\n\n")

快速回顾;我正在设置一个名为 data 的变量,它包含 .dat 文件中的所有数据,然后我想将该变量保存到 .txt 文件,但是每当我将它保存到 .txt 文件时,它的内容是.dat 文件,即使当我调用 print(data) 它以正常、清晰的文本告诉我数据时。感谢您的帮助。

with open(f"{split}_convert.txt", "wb") as fp:
    pickle.dump(data, fp)

当您以wb 模式打开文件时,它会自动向其中写入二进制数据。要将纯文本写入 .txt 文件,请使用

with open(f"{split}_convert.txt", "w") as fp:
    fp.write(data)

因为data是一个列表,所以也不能直接写出来。您需要使用循环编写每个项目。

with open(f"{split}_convert.txt", "w") as fp:
    for line in data:
        fp.write(line)

有关文件写入的更多详细信息,请同时查看这篇文章:https://www.tutorialspoint.com/python3/python_files_io.htm