Python: 使用 while 循环写入文件失败,没有给出错误

Python: Writing to file using while loop fails with no errors given

我试图从一个文件中仅收集特定类型的数据。之后,数据将被保存到另一个文件中。由于某种原因写入的功能没有保存到文件中。代码如下:

def reading(data):
file = open("model.txt", 'r')
while (True):
    line = file.readline().rstrip("\n")
    if (len(line) == 0):
        break
    elif (line.isdigit()):
        print("Number '" + line + "' is present. Adding")
file.close()
return None

def writing(data):
    file = open("results.txt", 'w')
    while(True):
        line = somelines
        if line == "0":
            file.close()
            break
        else:
            file.write(line + '\n')
    return None

file = "model.txt"
data = file
somelines = reading(data)
writing(data)

我尝试了几件事,上面的那个产生了类型错误(不支持的操作数)。更改为 str(somelines) 确实解决了错误,但仍然没有写入任何内容。我对此很困惑。是写函数中对“线”的定义有误吗?或者别的什么?

在您的 writing 函数中查看这一行:

            file.write(line + '\n')

你在哪里

        line = somelines

在你拥有的功能之外

somelines = reading(data)

您创建了 reading 函数 return None。您不能将 None 与任何字符串连接,因此会出现错误。

假设您需要一种扫描输入文件中数字的读取功能,以及一种将这些数字写入文件直到读取的数字为 0 的写入文件,这可能会有所帮助:

def reading(file_name):
    with open(file_name, 'r') as file:
        while True:
            line = file.readline().rstrip("\n")
            if len(line) == 0:
                break
            elif line.isdigit():
                print("Number '" + line + "' is present. Adding")
                yield line

def writing(results_file, input_file):
    file = open(results_file, 'w')
    digits = reading(input_file)
    for digit in digits:
        if digit == "0":
            file.close()
            return
        else:
            file.write(digit + '\n')
    file.close()

writing("results.txt", "model.txt")