多次操作文件数据

时间:2016-01-02 18:04:42

标签: python string list file

我在文件操作方面遇到了一些麻烦。我想操作数据2次,并将最后操作的数据写入同一个文件。

这是我操纵的档案:

['Simon', 93.45000000000002, 'AA']
['Jane', 87.55000000000001, 'BA']
['Peter', 85.95, 'BA']

这是我的代码,用于更改文件中的数据。

for line in manipulated_file:
    line=line.split()
    list_to_be_written=[]
    for i in line:
        i=i.replace("['","")
        i=i.replace("'","")
        i=i.replace(",",":")
        i=i.replace("]","")
        list_to_be_written.append(i)
    list_to_be_written=" ".join(list_to_be_written)
    print list_to_be_written

如果我无法将输出写入文件,它完全运行..

同一文件中的预期输出:

Simon: 93.45000000000002: AA
Jane: 87.55000000000001: BA
Peter: 85.95: BA

提前谢谢。

3 个答案:

答案 0 :(得分:3)

您可以使用ast.literal_eval

from ast import literal_eval

with open('demo.txt','r') as input_file, open('output.txt','a') as output:
    for line in input_file:
        temp = literal_eval(line)
        output.write(": ".join([repr(a) if type(a)== float else a for a in temp])+'\n')

output.txt的内容:

Simon: 93.45000000000002: AA
Jane: 87.55000000000001: BA
Peter: 85.95: BA

答案 1 :(得分:2)

您可以使用ast.literal_eval来解析列表,使用fileinput.input来更改原始文件。

import fileinput
from ast import literal_eval
import sys


for line in fileinput.input("in.txt", inplace=1):
    sys.stdout.write(": ".join(map(str, literal_eval(line))) + "\n")

哪个会给你:

Simon: 93.45000000000002: AA
Jane: 87.55000000000001: BA
Peter: 85.95: BA

您也可以通过拆分和剥离来实现:

import fileinput
import sys
for line in fileinput.input("in.txt", inplace=True):
    sys.stdout.write(":".join([w.strip("'") for w in line.strip("[]\n").split(", ")]) + "\n"

它为您提供相同的输出:

Simon: 93.45000000000002: AA
Jane: 87.55000000000001: BA
Peter: 85.95: BA

如果代码出现错误,您将丢失数据,因此更好的选择可能是写入tempfile,然后执行shutil.move

from shutil import move
from tempfile import NamedTemporaryFile

with open("in.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
    for line in f:
        tmp.write(": ".join([w.strip("'") for w in line.strip("[]\n").split(", ")]) + "\n")

move(tmp.name,"in.txt")

答案 2 :(得分:1)

我相信如果你想将你的数据写入与初始数据相同的文件中,你必须首先打开它进行读取,读取变量,处理它,然后打开它进行写入并写下所有的数据。需要。有关详细信息,请参阅the docs

with open("file.txt", "r") as manipulated_file:
    manipulated_file_lines = manipulated_file.readlines()
with open("file.txt", "w") as  manipulated_file:

    for line in manipulated_file_lines:
        line=line.split()
        list_to_be_written=[]
        for i in line:
            i=i.replace("['","")
            i=i.replace("'","")
            i=i.replace(",",":")
            i=i.replace("]","")
            list_to_be_written.append(i)
        list_to_be_written=" ".join(list_to_be_written)
        print list_to_be_written

        manipulated_file.write(list_to_be_written)

P.S。我不确定你是否必须以这种方式手动处理你的线。我相信最好用json解码器将它们转换为Python对象(例如list),然后从该对象格式化输出字符串。这可以用来代替那些.replace()

import json
with open("file.txt", "r") as manipulated_file:
    manipulated_file_lines = manipulated_file.readlines()
with open("file.txt", "w") as  manipulated_file:
    for line in manipulated_file_lines:
        processed_list = json.loads(line.replace("'",'"'))
        list_to_be_written=": ".join(map(str,processed_list))
        # this should be tweaked if you want full precision for numbers

        print list_to_be_written

        manipulated_file.write(list_to_be_written)

您也可以使用ast.literal_eval代替json.loads,请参阅the docsthis question