Python:在文件中保存大条目

2024-03-29 13:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个文件(不介意类型)中保存一些关于条目和对象的字符串信息。我可以从我的数据中生成字符串,并且我知道如何将字符串保存在.txt文件中。但是,当我从文件中读取时,我读取的是“行”,所以我假设它读取一行直到第一个新行符号。但是,我的一些字符串比文档行长,当我想读取它时,会出现错误。如何在文件中保存长字符串以不丢失任何数据

这就是我在文件中保存的方式:

with codecs.open(filename, 'a', "utf-8") as outfile:
    outfile.write(data_string + '\n')

以及我如何从文件中读取数据:

with codecs.open(filename, 'r',"utf-8") as infile:
    lines = infile.readlines()

Tags: 文件数据对象字符串信息类型aswith
1条回答
网友
1楼 · 发布于 2024-03-29 13:00:44

您有几个选择:

转储/加载为JSON

import tempfile
import json

text = 'this is my string with a \nnewline in it'

with tempfile.TemporaryFile(mode='w+') as f:
    f.write(json.dumps([text]))
    f.flush()
    f.seek(0)
    lines = json.load(f)
    print(lines)

缺点:JSON可能是相当可读的,但是文件中的一个小错误会破坏一切。不像普通的文字那么清晰

泡菜

import tempfile
import pickle

text = 'this is my string with a \nnewline in it'

with tempfile.TemporaryFile(mode='w+') as f:
    f.write(pickle.dumps([text]))
    f.flush()
    f.seek(0)
    lines = pickle.load(f)
    print(lines)

缺点:pickle是terribly insecure,你应该像对待eval一样对待它。如果在这种情况下使用eval会感到不舒服,那么就不应该使用pickle

你自己的sentinel

import tempfile

text = 'this is my string with a \nnewline in it'
other_text = 'this line has no newline in it'

with tempfile.TemporaryFile(mode='w+') as f:
    f.write(text)
    f.write(chr(30))
    f.write(other_text)
    f.flush()
    f.seek(0)
    lines = f.read().split(chr(30))
    print(lines)

缺点:可能有点棘手。你必须确保你的哨兵没有在文本中找到。另外,您不能使用readlines,逐行迭代会让您觉得有点尴尬

相关问题 更多 >