简体   繁体   English

读两行,写一行

[英]Reading two lines and writing in one line

I am new to python. 我是python的新手。 Using below mentioned code to get two lines as one in a another txt file 使用下面提到的代码将两行作为另一个txt文件中的一行

import glob

dirname = 'F:\\mmml'

list_of_files = glob.glob(dirname+'/*.mml')

with open("F:\\d.txt", "w") as fout:

        for fileName in list_of_files:
            for line in open(fileName, "r"):
                if line.startswith('MOD:') or line.startswith('EQUIPMENT:'):
                   fout.writelines(line)

But I am getting result in vertical order like 但是我得到的是垂直顺序的结果

MOD

EQUIPMENT

But I want output be 但我想输出是

MOD EQUIPMENT

I could not understand existing solutions for similar problems. 我无法理解类似问题的现有解决方案。

Your problem is that when you do for line in open(fileName, "r"): the newline ( \\r\\n / \\n ) at the end of line is still present. 你的问题是,当你做for line in open(fileName, "r"):换行符( \\r\\n / \\n在年底) line仍然存在。 So you just have to strip() the line to solve your problem: 因此,您只需要strip() line即可解决您的问题:

for line in open(fileName, "r"):
    if line.startswith('MOD:') or line.startswith('EQUIPMENT:'):
       fout.writelines(line.strip())

or use the splitlines method: 或使用splitlines方法:

for line in open(fileName, "r").read().splitlines():
    if line.startswith('MOD:') or line.startswith('EQUIPMENT:'):
       fout.writelines(line)

Note that you could do the last for loop in one line: 请注意,您可以在一行中执行最后一个for循环:

fout.writelines(' '.join(line.strip() for line in open(fileName, "r") \
    if line.startswith('MOD:') or line.startswith('EQUIPMENT:')))

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

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