读取标题,并在Python中用另一个替换列值

时间:2019-02-28 03:26:13

标签: python io

我是Python的新手,我正在尝试读取以下格式的文件

ORDER_NUMBER!Speed_Status!Days!
10!YES!100!
10!NO!100!
10!TRUE!100!

要写入同一文件的输出是

ORDER_NUMBER!STATUS!Days!
10!YES!100!
10!NO!100!
10!TRUE!100!

到目前为止我尝试过

# a file named "repo", will be opened with the reading mode. 
file = open('repo.dat', 'r+') 
# This will print every line one by one in the file 
    for line in file: 
        if line.startswith('ORDER_NUMBER'):
            words = [w.replace('Speed_Status', 'STATUS') for w in line.partition('!')]
            file.write(words)
input()

但是不知何故,它不起作用。我想念什么。

2 个答案:

答案 0 :(得分:1)

读取文件⇒替换内容⇒写入文件:

with open('repo.dat', 'r') as f:
    data = f.read()

data = data.replace('Speed_Status', 'STATUS')

with open('repo.dat', 'w') as f:
    f.write(data)

答案 1 :(得分:1)

理想的方法是使用fileinput模块就地替换文件内容,而不是在更新模式r+中打开文件

from __future__ import print_function
import fileinput

for line in fileinput.input("repo.dat", inplace=True):
    if line.startswith('ORDER_NUMBER'):
        print (line.replace("Speed_Status", "STATUS"), end="")
    else:
        print (line, end="")

关于您的尝试为何无效的原因,形成words的逻辑是很不正确的,当您基于!划分行时,您形成的列表是乱序的与['ORDER_NUMBER', '!', 'STATUS!Days!\n']和嵌入的换行符一样。同样,您的write()调用也绝不会使用非字符缓冲区对象。您需要将其转换为字符串格式才能打印。