Python - 我试图用新行拆分制表符分隔的文件,然后按制表符,然后在特定位置的每一行中添加数据
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
我正在尝试根据每一行拆分一个制表符分隔的文件,然后是每个制表符,然后将一段文本添加到每一行的特定位置。
即:
H123_123 78.752 绿色 7 0 0 0 0 1 基因
H1234_1234 23.998 绿色 9 1 0 0 0 0.92 基因
进入:
H123_123 78.752 NEW_TEXT 绿色 7 0 0 0 0 1 基因
H1234_1234 23.998 NEW_TEXT 绿色 9 1 0 0 0 0.92 基因
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()
当它被打印到终端时,它似乎是正确的格式...但是输出文件都在一行上 - “\n”不起作用?
有更好的方法吗?我一直在更改我的代码,但不断收到不同的错误代码
非常感谢
outputfile.write(str(lst) + '\n')
但是如果您想将列表转换为字符串,请使用 join() 方法
outputfile.write(' '.join(lst) + '\n')
我正在尝试根据每一行拆分一个制表符分隔的文件,然后是每个制表符,然后将一段文本添加到每一行的特定位置。
即: H123_123 78.752 绿色 7 0 0 0 0 1 基因 H1234_1234 23.998 绿色 9 1 0 0 0 0.92 基因
进入:
H123_123 78.752 NEW_TEXT 绿色 7 0 0 0 0 1 基因 H1234_1234 23.998 NEW_TEXT 绿色 9 1 0 0 0 0.92 基因
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()
当它被打印到终端时,它似乎是正确的格式...但是输出文件都在一行上 - “\n”不起作用? 有更好的方法吗?我一直在更改我的代码,但不断收到不同的错误代码
非常感谢
outputfile.write(str(lst) + '\n')
但是如果您想将列表转换为字符串,请使用 join() 方法
outputfile.write(' '.join(lst) + '\n')