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

时间:2018-09-27 20:34:13

标签: python

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

1 个答案:

答案 0 :(得分:0)

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

此外,将您的for循环更改为此:

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

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