如何在Python TXT文件中进一步拆分一条线?
我试图将一条线向下分成较小的元素,
每行都包含鸟类的名字及其已看到的次数。如果名称匹配,我正在尝试显示两者,但找不到进一步划分一行的方法。
这是我的代码:
with open("birdFile.txt", "w") as file:
numRecs = int(input("How many records do you wish to write? "))
for n in range(1,numRecs+1):
birdName = input("Enter bird name: ")
birdsReported = input("Enter number of bird reported: ")
file.write(birdName + birdsReported + ",")
with open("birdFile.txt", "r") as file:
birdNameSearch = input("What bird are you searching for? ")
for line in file:
file = line.split(",")
birdName = line[0]
birdsSeen = line[1]
if birdNameSearch == birdName:
print(birdName + ": " + birdsSeen)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您写了
通知,
,
逗号是在数字之后的 - 您想要它之前,要将名称与数字分开。
另外,您需要在行结束时
\ n
newline。这是通过F-string最方便完成的:
考虑使用CSV模块:
You wrote
Notice that the
,
comma came after the number -- you want itbefore, to separate name from number.
Also, you'll want a
\n
newline at end of line.This is most conveniently accomplished with an f-string:
Consider using the csv module: https://docs.python.org/3/library/csv.html