接受用户输入以读取文件中的这么多行

凯西恩(Kithion Prathaban)

我正在尝试接受用户输入以将许多行读入文本文件。到目前为止,我遇到了这个错误,但出现此错误:在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)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章