通过在文件内部进行数学运算来编辑文本文件

时间:2018-07-16 06:00:27

标签: python text-files text-editor

我有一个像这样的文本文件(text.txt):

50  10  15  20  25
40  30  35  40  45
30  50  55  60  65

我已如下编辑该文件:

lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')

for line in lines:
    line = line.split()

    output.write('Values({},{},{},{},{});\n'.format(line[0], line[1], 
line[2], line[3], line[4]))

output.close()

这是新的文本文件:

Values(50,10,15,20,25);
Values(40,30,35,40,45);
Values(30,50,55,60,65);

现在,我想通过对其组成部分进行数学运算来编辑文件(原始text.txt):

  1. 我想从第一个的所有分量中减去10 列

  2. 我想从其余部分的所有分量中减去1 列

更具体地说,我正在查看此内容:

Values(40,9,14,19,24);
Values(30,29,34,39,44);
Values(20,49,54,59,64);

如何在此文本文件中实现此简单的数学运算以获取上述结果作为输出? 谢谢!

2 个答案:

答案 0 :(得分:1)

尝试一下:

lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')

for line in lines:
    line = line.split()
    # subtract 10 from all of the components in the first column
    line[0] = int(line[0]) - 10
    # subtract 1 from all of the components in the rest of the columns
    line[1:] = [int(n) - 1 for n in line[1:]]
    output.write('Values({},{},{},{},{});\n'.format(*line))

output.close()

答案 1 :(得分:0)

似乎您正在读取CSV文件。使用pandas库处理文件会容易得多。

import pandas as pd

# read the CSV file with space as delimiter
df = pd.read_csv('the.txt', delimiter=' ', header = None)
df.head()

# there are two spaces, so a the number of columns is twice
# remove the columns with NaN values
df = df.dropna(axis=1, how='all')
df.head()

# subtract the column one by 10
df[0] = df[0].apply(lambda x: x - 10)
df.head()

# subtract the rest of the columns by 1
df[[2,4,6,8]] = df[[2,4,6,8]].apply(lambda x: x -1)
df.head()

# convert the dataframe to tuples
records = [tuple(x) for x in df.to_records(index=False)]

# Write the records to the the file
with open('a.txt','w') as outfile: 
    for record in records:
        outfile.write('Values{};\n'.format(record))