如何在文本中添加每行的副本(包含由特定符号分隔的两个部分),两个部分的顺序是否相反?

时间:2012-02-05 02:13:09

标签: python shell scripting

我有一些行(x @ y)的txt。每个文件有两个部分(x,y),由特定符号(@)分隔。 python脚本如何读取txt中的每一行,并在每个现有行下添加一个新行,其中两个部分(x @ y)的顺序被反转(y @ x)。

我正在尝试做的输入/输出:

INPUT:

x1@y1
x2@y2
x3@y3

输出:

x1@y1
y1@x1
x2@y2
y2@x2
x3@y3
y3@x3

如何用python完成?

6 个答案:

答案 0 :(得分:2)

这是一种方式:

infilename = 'in.dat'
outfilename = 'out.dat'
sep = '@'

with open(infilename) as infile, open(outfilename,'w') as outfile:
    for line in infile:
        split = line.strip().partition(sep)
        outfile.write(line)
        outfile.write(''.join(reversed(split)) + '\n')

然后

~/coding$ cat in.dat 
x1@y1
x2@y2
x3@y3
~/coding$ python inverter.py 
~/coding$ cat out.dat 
x1@y1
y1@x1
x2@y2
y2@x2
x3@y3
y3@x3

答案 1 :(得分:0)

有更简洁的方法可以做到这一点,但你可以使用类似的东西:

f = open('my_file.txt', 'r')
lines = f.readlines()
f.close()

outfile = open('my_file2.txt', 'w')

# write each line, followed by flipped line
for line in lines:
    outfile.write('%s\n' % line)
    parts = line.split('@')
    outfile.write('%s@%s\n' % [parts[1], parts[0]])

outfile.close()

答案 2 :(得分:0)

您可以使用openread功能阅读file而不是使用此功能,

>>> st = "x1@y1"
>>> def myfunc(string):
...       mylist = re.split(r'(@)',string)
...       mylist.reverse()
...       print "".join(mylist), string
...
>>> myfunc(st)
y1@x1 x1@y1

而不是使用write将字符串写入新文件。

答案 3 :(得分:0)

def swap(delimiter="@", input="input.txt", ouput="output.txt"):
    with open(input, "r") as input_file, open(ouput, "w") as output_file:
            for line in input_file:
                line = line.strip()
                output_line = delimiter.join(reversed(line.split(delimiter)))
                output_file.write(line+"\n")
                output_file.write(output_line+"\n")

swap()

答案 4 :(得分:0)

假设您的文件名是bar.txt,并且您想将其写回bar.txt。它也没有错误检查也不关心内存使用情况。

if __name__ == "__main__":
    myfile = open("bar.txt", "rb")
    lines = myfile.readlines()
    myfile.close()

    myfile = open("bar.txt", "wb")
    for l in lines:
        ls = l.strip()
        myfile.write(ls + "\n")
        lsplit = ls.split("@")
        myfile.write(lsplit[1] + "@" + lsplit[0] + "\n")

    myfile.close()

答案 5 :(得分:0)

在@DSM上徘徊:

with open(infilename) as infile, open(outfilename, 'w') as outfile:
    lines = [line.rstrip() for line in infile]
    outfile.write("\n".join("%s\n%s%s%s" (line, y, sep, x)
        for line in lines
        for x, y in line.split(sep)) + "\n")

lines也可以是生成器语句而不是列表推导:

lines = (line.rstrip() for line in infile)

后来:直到现在我才意识到OP需要原线然后是反转线。相应调整。