Python CSV模块,将列添加到侧面,而不是底部

时间:2012-11-30 03:56:09

标签: python csv

我是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)

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

我的第一个脚本工作“几乎”很好,除了它在底部写下新列,我需要它们在前面列的一侧。

1 个答案:

答案 0 :(得分:1)

使用writerow的正确方法是为其提供一个包含所有列数据的列表。

words.append(word1)
words.append(word2)
writer.writerow(words)