简体   繁体   English

使用 Python 替换文本文件中一行中的一列

[英]Replace one column in a line in a text file using Python

I have a text file and it has the following contents我有一个文本文件,它有以下内容

    #                                       
    #   Keywords:                                   
    #                                                                           
    LiFePO4                                     
    end                                     
    name    Li5FeO4                                 
    cell                                        
        18.557309   18.316802   9.125725    90.047539   90.100646   90.060551 0 0 0 0 0 0           
    fractional  1                                   
    Li  core    0.06001     0.059408    0.849507    1   1   0   0   0   0
    Li1 core    0.025416    0.339078    0.128746    1   1   0   0   0   0
    Li2 core    0.02517     0.838929    0.130747    1   1   0   0   0   0
    Li3 core    0.525498    0.339179    0.127632    1   1   0   0   0   0
    Li4 core    0.524753    0.841333    0.129329    1   1   0   0   0   0
    Li5 core    0.179907    0.158182    0.634012    1   1   0   0   0   0
    Li6 core    0.180817    0.666028    0.628327    1   1   0   0   0   0

This is the input that I need to supply to a tool which used in some research application.这是我需要提供给在某些研究应用中使用的工具的输入。 Now I need to replace the 0 on the first line which starts with Li on the third column from the last.现在我需要替换第一行的0 ,它从最后一列的第三列以Li开头。 That is, there are four zeros towards the end in each of the lines starting with Li .也就是说,以Li开头的每一行的末尾都有四个零。 I need to replace the second zero and so the file will have the the contents as follows:我需要替换第二个零,因此文件的内容如下:

    #                                       
    #   Keywords:                                   
    #                                                                           
    LiFePO4                                     
    end                                     
    name    Li5FeO4                                 
    cell                                        
        18.557309   18.316802   9.125725    90.047539   90.100646   90.060551 0 0 0 0 0 0           
    fractional  1                                   
    Li  core    0.06001     0.059408    0.849507    1   1   0   1   0   0
    Li1 core    0.025416    0.339078    0.128746    1   1   0   0   0   0
    Li2 core    0.02517     0.838929    0.130747    1   1   0   0   0   0
    Li3 core    0.525498    0.339179    0.127632    1   1   0   0   0   0
    Li4 core    0.524753    0.841333    0.129329    1   1   0   0   0   0
    Li5 core    0.179907    0.158182    0.634012    1   1   0   0   0   0
    Li6 core    0.180817    0.666028    0.628327    1   1   0   0   0   0

This has to be done a number of times for the zeros in various positions and I have the following code.对于各个位置的零,必须多次执行此操作,并且我有以下代码。 There are some more operations that I am doing in the same code.我在相同的代码中执行了更多操作。

import os
import shutil
import time


def edit_file(column, next_column):
    # Processing x.gin file
    file_name = './' + column + '.gin'
    file_handler = open(file_name, 'r')
    print("Processing " + file_name + " file")
    contents = file_handler.readlines()
    find_line = contents[14]
    find_line_array = find_line.split('\t')

    print(find_line_array)

    # change values according to the file name
    if column == 'x':
        find_line_array[8] = 1
    elif column == 'y':
        print(contents)
        print(find_line_array)
        find_line_array[9] = 1
    elif column == 'z':
        find_line_array[10] = 1
    elif column == 'xy':
        find_line_array[8] = 1
        find_line_array[9] = 1
    elif column == 'yz':
        find_line_array[9] = 1
        find_line_array[10] = 1
    elif column == 'xz':
        find_line_array[8] = 1
        find_line_array[10] = 1

    formatted = '\t'.join(map(str, find_line_array))
    contents[14] = formatted
    with open(file_name, 'w') as f:
        for item in contents:
            f.write("%s\n" % item)
    print("Formatting completed for " + file_name)

    print('Executing GULP command ----')

    gulp_command = 'gulp ' + column + '.gin > ' + column + '.gout'
    print(gulp_command)
    shutil.copy(file_name, next_column+'.gin')

    file_handler.close()
    os.system(gulp_command)

    while not os.path.exists('./Li.grs'):
        print('Waiting for output file')
        time.sleep(1)

    if os.path.isfile('./Li.grs'):
        print('renaming file')
        os.rename('./Li.grs', next_column+'.gin')
        os.rename('./Li.grs', column+'.grs')

    return True


if __name__ == '__main__':
    print('Starting Execution')
    column_list = ['x', 'y', 'xy', 'yz', 'xz']
    print(column_list)
    for index, column in enumerate(column_list):
        if column != 'xz':
            edit_file(column, column_list[index + 1])
        else:
            edit_file(column, 'xz')
    print('Execution completed')

I am replacing it correctly and rewriting the file.我正在正确替换它并重写文件。 But this file doesn't appears to be in correct format as it has additional new lines.但是这个文件的格式似乎不正确,因为它有额外的新行。 Is it possible that I can rewrite the single line only and so that I can keep the file in exact same format.是否有可能我只能重写单行,以便我可以将文件保持在完全相同的格式。

i created a function for that.我为此创建了一个 function。 try this尝试这个

def replace(filename,row,column,value):
    columnspan = "     "
    data = open(filename).read().split("\n")
    for i in range(len(data)):
        data[i] = data[i].split(columnspan)
    data[row][column] = value
    write=""
    for i in range(len(data)):
        for x in range(len(data[i])):
            write+=(str(data[i][x])+columnspan)
        write += "\n"
    write.strip()
    file = open(filename,"w")
    file.write(write)
    file.close()

You can use regex to find and update text:您可以使用regex来查找和更新文本:

import re

with open('input.txt', 'r') as f1, open('output.txt', 'w') as f2:
    data = f1.read()
    match = re.findall('Li\s+\w+\s+\d+\.\d+\s+\d\.\d+\s+\d\.\d+\s+\d\s+\d\s+\d\s+\d', data)
    for m in match:
        data = data.replace(m, f'{m[:-1]}1')
    f2.write(data)

Output: Output:

#
#   Keywords:
#
LiFePO4
end
name    Li5FeO4
cell
    18.557309   18.316802   9.125725    90.047539   90.100646   90.060551 0 0 0 0 0 0
fractional  1
Li  core    0.06001     0.059408    0.849507    1   1   0   1   0   0
Li1 core    0.025416    0.339078    0.128746    1   1   0   0   0   0
Li2 core    0.02517     0.838929    0.130747    1   1   0   0   0   0
Li3 core    0.525498    0.339179    0.127632    1   1   0   0   0   0
Li4 core    0.524753    0.841333    0.129329    1   1   0   0   0   0
Li5 core    0.179907    0.158182    0.634012    1   1   0   0   0   0
Li6 core    0.180817    0.666028    0.628327    1   1   0   0   0   0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM