如何在循环中修改文本文件的特定行?

0 投票
4 回答
829 浏览
提问于 2025-04-18 16:01

我正在使用 Python 2.7(操作系统是 CentOS 6)。

我有一个文本文件,里面的内容大概是这样的:

0     4.064  16.786   7.016    0
1     5.520  14.733   5.719    0
2     5.904  17.898   5.222    0
3     3.113  18.613  18.453    0
4     3.629  16.760   5.118    0
            :
            :
            :
398   6.369  14.623    6.624    0
399   5.761  18.084    7.212    0
400   2.436  17.021   10.641    0

最后一列最开始都是 0,这其实是一个标志位。我想修改这个文本文件,也就是说,我想把最后一列的值改成 1(也就是把标志位的值改成 1),每当某个条件满足时,就进行修改。比如说,行号 3、20、250、400 满足这个条件。那么我想把这些特定行的标志位(最后一列的值)改成 1,而不改变这些行上的其他值。 另外,我想在循环中进行这个操作,因为我有很多条件需要检查。因此,我每次都得从文件的顶部开始,逐行扫描;每当满足条件时,就把该行的标志位改成 1。

重要的是:我会使用同一个修改过的文件来选择那些标志位不是 1 的行(以便进行进一步处理)。在上面提到的每次循环中,我想读取这个修改过的文件。这意味着,简单来说,我想先修改文件(也就是把标志位设为 1)以满足一个条件,然后读取修改过的文件,进行处理,再检查下一个条件,继续把这个条件的标志位设为 1,读取修改过的文件,依此类推。

我还想补充一点:每次需要满足的条件都涉及到两行不同的内容。比如说,如果第 3 行和第 398 行的第二列的差值小于 2.0,那么就把第 398 行的标志位设为 1。也就是说,差值 17.898 - 18.084 小于 2.0,所以第 398 行的标志位会被设为 1。

任何帮助都将非常感谢。

4 个回答

0

好的。首先,你需要打开文件,然后逐行读取内容。

我建议你从一个文件中逐行读取,然后把这些内容写入到另一个文件里。

with open("original.dat", "r"), open("new.dat", "w") as source, destination:
    for line in source:
        # split on spaces is the default:
        line_no, v1, v2, v3, flag = line.split()
        # just an example, do whatever checks you need to
        should_set_flag = some_computation(v1, v2, v3)
        if should_set_flag: 
            flag = 1
        destination.write("{} {} {} {} {}\n".format(line_no, v1, v2, v3, flag))

也许我没有理解你每次修改时都要读取整个文件的需求。因为这些行之间似乎是独立的,我不太明白为什么这样做是必要的。

0
    f=open("filename",'r')
    data=f.readlines()
    f.close()
    #remove file by using os.rm or using subprocess
    i=0
    while i < len(data):
          #do something
          #make changes to data list
    f=open("filename",'w')
    f.write(data)

这可能是唯一的方法。先加载数据,删除旧文件,然后进行修改,最后写入一个新文件。

0

为什么你需要把文件写回去呢?文件只有400行,你可以把这些行保存在内存里,然后一行一行地处理。

def is_criterion_1_fulfilled(row):
    return row[1]<4 # only an example

def process_1(row):
    print row # or do anything else with the line

def filter_and_process(iterator, criterion, process):
    for row in iterator:
        if criterion(row):
            continue
        process(row)
        yield row

def main():
    with open(filename, 'r') as inp:
        dataset = [map(float, line.split()) for line in inp]
    dataset = list(filter_and_process(dataset, is_criterion_1_fulfilled, process_1))
    dataset = list(filter_and_process(dataset, is_criterion_2_fulfilled, process_2))
    ....

if __name__ == '__main__':
    main()
0
# Imports
import re

# Functions
def check_data(record, records):
    # TODO Implement check operation
    return False

# Read input data
infile = "data.txt"
with open(infile, "r") as f:
    # Make a list of lists
    records = [re.split('\s+',record) for record in f.read().splitlines()]

# Process the data
for i, record in enumerate(records):
    # enumerate so as to refer to ith record if necessary,
    # but lineno anyway available in record[0]
    if check_data(record, records):
        record[4] = '1'


# Write modified data
outfile = "out%s" % infile
with open(outfile, "w") as f:
    for record in records:
        f.write('\t'.join(record)+'\n')

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

撰写回答