Python:按标签分割txt文件 [英] Python: Splitting txt file by tab

查看:305
本文介绍了Python:按标签分割txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先是python的新手,但是不擅长它...我正在尝试打开一个名为bestsellers.txt的txt文件.在文本文件中,它用制表符分隔,例如

first off new to python and not good at it... I am trying to open a txt file called bestsellers.txt. In the text file it is split by a tab character for example,

1st to Die    James Patterson    Little, Brown    3/25/2001    Fiction 

因此,在Die之后,制表符的间隔与在Patterson和Brown和2001之后的间隔相同 我现在所拥有的只是

So, after Die it is tab spaced same with after patterson and brown and 2001 All I have right now is

openBook = open('bestsellers.txt', 'r')
booklist = openBook.split('\t')

但是,它似乎不起作用,建议怎么做?我必须保持简单. 我知道这可能也是一个愚蠢的问题,所以我深表歉意...

But, it doesn't seem to work, suggestions on what to do? I have to keep it simple. I know this is probably a dumb question as well, so I apologize...

推荐答案

要在每个选项卡上进行拆分,请依次遍历文件:

To split at each tab, iterate over the file like so:

data = [i.strip('\n').split('\t') for i in open('bestsellers.txt')]

这篇关于Python:按标签分割txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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