简体   繁体   English

替换一个字符并在每行中添加“大于符号”

[英]Replace a character and add 'greater than sign' in each line

Input:输入:

Aa Ab,Ac,Ad
Ba Bb,Bc,Bd
Ca Cb,Cc,Cd

Expected output:预期 output:

>Aa,Ab,Ac,Ad
>Ba,Bb,Bc,Bd
>Ca,Cb,Cc,Cd

Output: Output:

>A
>a
>,
>A
>b
 :
>C
>d

Code:代码:

with open(input, 'r') as fr, open(add_greater_than_sign, 'a') as fa:

    while True:
        line = fr.readline()
        line_replaced = line.replace('\t',',')
    
        appendText='>'
        for name in line_replaced:
            fa.write(appendText + name.rstrip() + '\n')
    
        if not line:
            break

I tried to replace a character and add 'greater than sign' in each line with this code.我试图用这段代码替换一个字符并在每一行中添加“大于符号”。 However, the result was like 'Output' file.但是,结果就像“输出”文件。 Could you let me know what is wrong?你能告诉我有什么问题吗?

In your for name in line_replaced: you loop over each character of a line and write one line per character.在你的for name in line_replaced:你遍历一行的每个字符,每个字符写一行。

Keep it simple:把事情简单化:

with open(input, 'r') as fr, open(add_greater_than_sign, 'a') as fa:
    for line in fr:
        fa.write('>'+line.replace('\t', ','))

NB.注意。 avoid using input as variable name, this is a python builtin避免使用input作为变量名,这是一个 python 内置

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

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