读取标题并用Python中的另一列值替换列值

读取标题并用Python中的另一列值替换列值,python,io,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 =

我是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()

但不知怎么的,它不起作用。我遗漏了什么。

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

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)

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

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)

理想的方法是使用
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="")

至于您的尝试失败的原因,当您基于
划分行时,形成
单词的逻辑是非常不正确的,您形成的列表的顺序不正确,如嵌入新行的
['order_NUMBER','!','STATUS!Days!\n']
。另外,您的
write()
调用永远不会接受非字符缓冲区对象。您需要将其转换为字符串格式才能打印。

理想的方法是使用
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="")

至于您的尝试失败的原因,当您基于
划分行时,形成
单词的逻辑是非常不正确的,您形成的列表的顺序不正确,如嵌入新行的
['order_NUMBER','!','STATUS!Days!\n']
。另外,您的
write()
调用永远不会接受非字符缓冲区对象。您需要将其转换为字符串格式才能打印。

您有if line.startswith('PART\u NUMBER'):可能需要将PART\u NUMBER更改为ORDER\u numberyah..抱歉..更改了…您有if line.startswith('PART\u NUMBER')):可能想将零件号更改为订单号eah..抱歉..更改了…这可能是@Programmerzzz想要的,但我只是想指出,也许,他只想替换以“零件号”或真正的“订单号”开头的行。这可能是@Programmerzzz想要的,但我只是想指出,也许,他只想替换以“零件号”或真正的“订单号”开头的行。