问题
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
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...
回答1:
To split at each tab, iterate over the file like so:
data = [i.strip('\n').split('\t') for i in open('bestsellers.txt')]
回答2:
openBook is a file, not a string. Even if it were a string, you'd want to iterate over the lines, and split each line on the tabs. So something like this:
with open("bestsellers.txt") as bookfile:
for line in bookfile:
fields = line.split("\t")
# now do something with this book's fields
But a better solution is to not reinvent the wheel and instead use the csv module, which is intended for reading various kinds of text files.
回答3:
You will need something along these lines:
for line in open(document).readlines():
line.split("\t")
来源:https://stackoverflow.com/questions/46918404/python-splitting-txt-file-by-tab