1

我是 python 新手,我需要一些帮助。我制作了一个 python 脚本,它从一个文件中获取两列并将它们复制到一个“新文件”中。但是,我不时需要向“新文件”添加列。我需要在侧面而不是底部添加列。我的脚本将它们添加到底部。有人建议使用 CSV,我读过它,但我无法将新列添加到先前列的一侧。非常感谢任何帮助。

这是我写的代码:

import sys
import re

filetoread = sys.argv[1]
filetowrite = sys.argv[2]

newfile = str(filetowrite) + ".txt"

openold = open(filetoread,"r")
opennew = open(newfile,"a")

rline = openold.readlines()

number = int(len(rline))
start = 0

for i in range (len(rline)) :
    if "2theta" in rline[i] :
        start = i

for line in rline[start + 1 : number] :
    words = line.split()
    word1 = words[1]
    word2 = words[2]
    opennew.write (word1 + " " + word2 + "\n")

openold.close()
opennew.close()

这是我使用 CSV 编写的第二个代码:

import sys
import re
import csv

filetoread = sys.argv[1]
filetowrite = sys.argv[2]

newfile = str(filetowrite) + ".txt"

openold = open(filetoread,"r")

rline = openold.readlines()

number = int(len(rline))
start = 0

for i in range (len(rline)) :
    if "2theta" in rline[i] :
        start = i

words1 = []
words2 = []

for line in rline[start + 1 : number] :
    words = line.split()
    word1 = words[1]
    word2 = words[2]
    words1.append([word1])
    words2.append([word2])

with open(newfile, 'wb') as file:
    writer = csv.writer(file, delimiter= "\n")
    writer.writerow(words1)
    writer.writerow(words2)

这些是输入文件的一些示例:

我的第一个脚本“几乎”工作得很好,除了它将新列写在底部并且我需要它们在前面的列旁边。

4

1 回答 1

1

正确的使用方法writerow是给它一个包含所有列数据的列表。

words.append(word1)
words.append(word2)
writer.writerow(words)
于 2012-11-30T04:37:21.517 回答