Home > OS >  Python: using .split() on an external text file
Python: using .split() on an external text file

Time:12-01

with open('books2.txt', 'rt') as f:
    data = f.readlines()
for line in data:
    if 'Fiction' in line:
        line.split(' ,')
        print(line)

The above is my current code and the output is as following

The Great Gatsby, Fiction, Fitz Gerald,11/11/2021,0

How would i be able to split each line via the comma and print each split onto a new line?:

The Great Gatsby
Fiction
Fitz Gerald
etc

CodePudding user response:

Split by "," and then remove white space from the splits. Join them with a "\n".

print("\n".join([ s.strip() for s in string.split(",")]))

output:

The Great Gatsby
Fiction
Fitz Gerald
11/11/2021
0
  • Related