简体   繁体   English

每隔一行添加一个空格,并在文本文件中每隔一行合并 Python

[英]Add a whitespace to every second line and merge every second line in a text file Python

I have a text file of lets say this content我有一个文本文件让我们说这个内容

a
b
c
d
e
f

I want python to read the textfile and edit it to this, add whitespace to the start of every second line then merge with first line above, this is what it should look like我想要 python 读取文本文件并将其编辑为这个,在每一行的开头添加空格然后与上面的第一行合并,这应该是这样的

a b
c d
e f

How can I achieve this?我怎样才能做到这一点?

I written gotten this together but it only prints and doesn't save the contents to existing file, doesn't add white space我把它写在一起,但它只打印并且不将内容保存到现有文件中,不添加空格

with open("text.txt", encoding='utf-8') as f:
    content = f.readlines()
    str = ""
    for i in range(1,len(content)+1):
        str += content[i-1].strip()
        if i % 2 == 0:
            print(str)
            str = ""

I would suggest differnt approch this also may works.我会建议不同的方法,这也可能有效。

with open("text.txt") as file_in:
lines = []
for line in file_in:
    lines.append(line)

#lines ['a\n', 'b\n', 'c\n', 'd']

lines = [x.replace('\n', '') for x in lines]
for x in range(0,len(lines),2):
    print (lines[x], lines[x+1])

should give应该给

a b
c d
e f

or else you can simply append spaces to list as follows and print accordingly.或者你可以简单地 append 空格来列出如下并相应地打印。

for b in range (0,len(lines)-1):
    
    lines.insert(b*3,' ') 

lines.pop(0) # ['a', 'b', ' ', 'c', 'd', ' ']
lines= ''.join(lines)
for word in lines.split():
    print(word)

Gives给予

ab
cd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM