简体   繁体   中英

Python - Im trying to split a tab delimited file by new line, then by tab, then add data in each line at a specific place

I am trying to split a tab delimited file based on each line, then each tab, then add a piece of text into a specific location in each line.

Ie: H123_123 78.752 GREEN 7 0 0 0 0 1 Gene H1234_1234 23.998 GREEN 9 1 0 0 0 0.92 Gene

Into:

H123_123 78.752 NEW_TEXT GREEN 7 0 0 0 0 1 Gene H1234_1234 23.998 NEW_TEXT GREEN 9 1 0 0 0 0.92 Gene

my_file = open("data.txt", "r+")
output = "data" + "_processed" + ".txt"
outputfile = open(output, "w")

run = NEW_TEXT

lst = []
for line in my_file:
    word = line.split("\t")
    if 'H' in line:
        lst = word[0:12]
        lst.insert(1, run)
        lst.insert(13, "\n")
        print lst
        outputfile.write(str(lst))
my_file.close()
outputfile.close()

when this is printed to the terminal it seems to be in the correct format... however the outputfile is all on one row - the "\\n" did not work? Is there a better way of doing this? I have been changing my code around but keep getting different error codes

Thanks alot

outputfile.write(str(lst) + '\n')

但是,如果要将列表转换为字符串,请使用join()方法

outputfile.write(' '.join(lst) + '\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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