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 Great Gatsby, Fiction, Fitz Gerald,11/11/2021,0
我怎样才能通过逗号拆分每一行并将每个拆分打印到一个新行上?:
The Great Gatsby
Fiction
Fitz Gerald
etc
用“,”拆分,然后从拆分中删除白色 space。用“\n”加入他们。
print("\n".join([ s.strip() for s in string.split(",")]))
输出:
The Great Gatsby
Fiction
Fitz Gerald
11/11/2021
0
with open('books2.txt', 'rt') as f:
data = f.readlines()
for line in data:
if 'Fiction' in line:
line.split(' ,')
print(line)
以上是我目前的代码,输出结果如下
The Great Gatsby, Fiction, Fitz Gerald,11/11/2021,0
我怎样才能通过逗号拆分每一行并将每个拆分打印到一个新行上?:
The Great Gatsby
Fiction
Fitz Gerald
etc
用“,”拆分,然后从拆分中删除白色 space。用“\n”加入他们。
print("\n".join([ s.strip() for s in string.split(",")]))
输出:
The Great Gatsby
Fiction
Fitz Gerald
11/11/2021
0