Python:删除一列,更改另一列,并在fi上写入输出

2024-03-29 07:14:29 发布

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

我在这个表格里有我的输入文本文件

1 2 3 4
5 6 7 8
9 10 11 12

我需要将其作为输入,删除最后一列,然后将第三列乘以一个常量值,例如10。所以最终的输出应该是这样的:

1 2 30 
5 6 70
9 10 110

所有这些都必须保存在一个单独的输出文件中。 如何在Python中实现这一点?你知道吗


Tags: 文件表格常量文本文件
3条回答

附言:只有样品。你知道吗

import csv
ff = open("output.csv","w") # added the line
csvwriter = csv.writer(ff)  # added the line
with open(file, "r") as logFile:
    reader = csv.reader(logFile,delimiter=" ")
    row = []
    for line in reader:
        col1 = lin[0]
        col2 = lin[1]
        col3 = int(lin[2]) * 10
        row = [col1,col2,col3]
        print row
        csvwriter.writerow(row)  # added the line
        del row[:]  # added the line
import pandas as pd
with open('textfile.txt') as f:
    df = pd.read_csv(f, header=None, sep=' ')

df = df.drop(3, 1)  # 3 = column name, 1 indicates columns
df[2] = df[2] * 10 
df.to_csv(r'output.txt', header=None, index=None, sep=' ', mode='a')

你可以试试这个:

f = [map(int, i.strip('\n').split()) for i in open('thefile.txt')]

new_f = [i[:-1] for i in f]

new_f = [i[:-1]+[i[-1]*10] for i in new_f]

new_file = open('final_file.txt', 'a')

for i in new_f:
    new_file.write(' '.join(map(str, i))+"\n")

new_file.close()

相关问题 更多 >