【发布时间】:2021-03-01 05:56:04
【问题描述】:
我有一个文本文件,它有以下内容
# #关键词: # 磷酸铁锂 结尾 名称 Li5FeO4 细胞 18.557309 18.316802 9.125725 90.047539 90.100646 90.060551 0 0 0 0 0 0 小数 1 锂芯 0.06001 0.059408 0.849507 1 1 0 0 0 0 Li1 核心 0.025416 0.339078 0.128746 1 1 0 0 0 0 Li2芯0.02517 0.838929 0.130747 1 1 0 0 0 0 Li3 核心 0.525498 0.339179 0.127632 1 1 0 0 0 0 Li4芯0.524753 0.841333 0.129329 1 1 0 0 0 0 Li5核心 0.179907 0.158182 0.634012 1 1 0 0 0 0 Li6核心 0.180817 0.666028 0.628327 1 1 0 0 0 0这是我需要提供给在某些研究应用中使用的工具的输入。现在我需要替换第一行上的0,它在倒数第三列上以Li 开头。也就是说,以Li 开头的每一行的末尾都有四个零。我需要替换第二个零,因此文件的内容如下:
对于不同位置的零,必须多次执行此操作,我有以下代码。我在同一个代码中还有一些操作。
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')
我正在正确替换它并重写文件。但是这个文件的格式似乎不正确,因为它有额外的新行。是否可以只重写单行,以便我可以保持文件格式完全相同。
【问题讨论】: