我想用Python列表替换文件的某一列

2024-04-18 16:10:44 发布

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

我有一个股票文件,看起来像这样:

12334232:seat belt:2.30:12:10:30
14312332:toy card:3.40:52:10:30
12512312:xbox one:5.30:23:10:30
12543243:laptop:1.34:14:10:30
65478263:banana:1.23:23:10:30
27364729:apple:4.23:42:10:30
28912382:orange:1.12:16:10:30
12892829:elephant:6.45:14:10:30

如果第四列中的项目在某个事务之后低于第五列中的数字,我想将它们替换为第四列中的数字。如何替换第四列中的项目? 每次我使用下面的代码行时,它都会覆盖整个文件而没有任何内容(删除所有内容)

for line in stockfile:
     c=line.split(":")
     print("pass")
      if stock_order[i] == User_list[i][0]:
        stockfile.write(line.replace(current_stocklevel_list[i], reorder_order[i] ) )
     else:
         i = i + 1

我希望stockfile在替换了列中的必要项后看起来像这样:

12334232:seat belt:2.30:30:10:30
14312332:toy card:3.40:30:10:30
12512312:xbox one:5.30:30:10:30
12543243:laptop:1.34:30::10:30
65478263:banana:1.23:30:10:30
27364729:apple:4.23:30:10:30
28912382:orange:1.12:30:10:30
12892829:elephant:6.45:30:10:30

Tags: 文件项目applelinecardonebananatoy
2条回答

如果在一段时间后打开文件,应该使用“a”(append)作为模式,这样文件就不会被截断。你知道吗

写入指针将自动位于文件末尾。你知道吗

所以:

f = open("filename", "a")
f.seek(0) # To start from beginning

但是如果您想读写,那么在模式中添加“+”,文件也不会被截断。你知道吗

f = open("filename", "r+")

读指针和写指针都在文件的开头,您只需要在希望开始写/读的位置上查找。你知道吗

但你做错了。你知道吗

请参阅,文件的内容将被覆盖,而不是自动插入。你知道吗

如果您处于可写模式,则在文件末尾将添加内容。你知道吗

所以,要么加载整个文件,进行所需的更改,然后写回所有内容。你知道吗

或者,您必须在某个点写入更改,并移动剩余内容,如果内容比以前短,则截断文件。你知道吗

mmap模块可以帮助您将文件视为字符串,。您将能够有效地移动数据和调整文件大小。你知道吗

但是,如果您真的想就地更改文件,则应该使用列长度固定的文件。因此,当您想要更改一个值时,不需要来回移动任何内容。只要找到正确的行和列,在那里查找,在旧的行和列上写下新的值(确保删除所有旧的值),就是这样。你知道吗

您应该先尝试读入数据:

with open('inputfile', 'r') as infile:
    data = infile.readlines()

然后,您可以在数据上循环,根据需要进行编辑并写出:

with open('outputfile', 'w') as outfile:
    for line in data:
        c = line.split(":")
        if random.randint(1,3) == 1:
            # update fourth column based on some good reason
            c[3] += 2
        outfile.write(':'.join(c) + '\n')

或者你可以这样做:

with open('inputfile', 'r') as infile, open('outputfile', 'w') as outfile:
    line = infile.readline()
    c = line.split(":")
    if random.randint(1,3) == 1:
        # update fourth column based on some good reason
        c[3] += 2
    outfile.write(':'.join(c) + '\n')

os.rename('outputfile', 'inputfile')

相关问题 更多 >