简体   繁体   English

Python:在外部文本文件上使用.split()

[英]Python: using .split() on an external text file

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以上是我当前的代码,output 如下

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

Split by "," and then remove white space from the splits.按“,”分割,然后从分割中删除空格。 Join them with a "\n".用“\n”加入他们。

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

output: output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM