gpt4 book ai didi

python - 获取用户输入来读取文件中的那么多行

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:18 25 4
gpt4 key购买 nike

我正在尝试接受用户输入以将那么多行读入文本文件。到目前为止我已经做到了,但收到此错误:在 write_dogs line=f.next().strip() AttributeError: '_io.TextIOWrapper' 对象没有属性 'next'

这是我现在的代码。

def write_dogs():
total_cards = int(input("How many cards do you wish to play with? "))
if total_cards %2 != 0:
print("Please enter an even number")
main_menu()
elif total_cards > 30 or total_cards < 4:
print("Please enter a number less that 30 and more than 4")
main_menu()
else:
N = total_cards
with open("dogs.txt") as f:
with open("dogswrite.txt", "w") as f1:
for i in range(N):
line=f.next().strip()
f1.write(line)

如有任何帮助,我们将不胜感激

工作代码如下

def write_dogs():
total_cards = int(input("How many cards do you wish to play with? "))
if total_cards %2 != 0:
print("Please enter an even number")
main_menu()
elif total_cards > 30 or total_cards < 4:
print("Please enter a number less that 30 and more than 4")
main_menu()
else:
N = total_cards
with open("dogs.txt") as f:#opens needed file
with open("dogswrite.txt", "w") as f1:#my own file to later create a class
for i in range(N):
line=next(f).strip()#lists the input number of results each on a new line
line = line + "\n"
f1.write(line)

最佳答案

.next() 在这里不起作用,因为 f 不是列表,而是文件。您应该使用 f.readline()

此外,将 for 循环更改为:

for i in range(N):
line=next(f).strip() + ', '
f1.write(line)

编辑:没有注意到索引行,还根据您的评论添加了逗号

关于python - 获取用户输入来读取文件中的那么多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com