将.txt文件中的第一行写为新.txt文件中的列 [英] Write first row from .txt-file as a column in new .txt-file

查看:94
本文介绍了将.txt文件中的第一行写为新.txt文件中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取file.txt(用 tab 分隔的字符串)的第一行,并创建一个新文件,该文件具有一列,该列由我要提取的行的元素组成.我设法得到了文件的第一行

I am trying to get the first row of a file.txt (tab separated strings) and create a new file with one column which is made of the elements of the row I want to extract. I managed to get the first row of the file with

f = open("file.txt", "r")
row1 = f.readline()

我在用x.T转置后尝试了("new_file.txt", w),但是没有用.得到文件后,我还应该分成10个较小的文件.

I tried the ("new_file.txt", w) after transposing with x.T but it didn't work. After I get the file I should also split in in 10 smaller files.

这是输入文件的示例:

rs123  rs15  rs1567  rs43  rs567  rs3564
    1     2       3     4      5       6
    7     8       9    10     11      12

这就是我所需要的:

rs123
rs15
rs1567
rs43
rs567
rs3564

推荐答案

with open('inFile.txt', 'r') as inFile, open('outfile.txt', 'w') as outFile:
    outFile.writelines(line + '\n' for line in inFile.readline().split('\t'))

要将文件拆分成较小的部分,我将使用unix split,例如:

To split the file in smaller parts I would use unix split, for example:

split -l $lines_per_file outfile.txt

要找到$lines_per_file,请将行wc -l output.txt的总行数除以10.

To find $lines_per_file divide the total number of lines wc -l output.txt by 10.

这篇关于将.txt文件中的第一行写为新.txt文件中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆