Python \";行连续字符“后出现意外字符”;

Python \";行连续字符“后出现意外字符”;,python,Python,在python中使用时,我遇到了一个反复出现的问题。我试图让代码在从另一个文本文件提取数据后写入文本文件,但是当我运行代码时,代码后面总是显示“行连续字符后出现意外字符”错误。\n。这是我目前正在使用的代码 while True: while True: try: Prod_Code = input("enter an 8 digit number or type Done to get your final receipt: ") check = le

在python中使用时,我遇到了一个反复出现的问题。我试图让代码在从另一个文本文件提取数据后写入文本文件,但是当我运行代码时,代码后面总是显示“行连续字符后出现意外字符”错误。\n。这是我目前正在使用的代码

while True:
 while True:
    try:
        Prod_Code = input("enter an 8 digit number or type Done to get your final receipt: ")
        check = len(Prod_Code)
        int(Prod_Code) 

        if check == 8:
            print("This code is valid")



            with open('Data Base.txt', 'r') as searchfile:
                for line in searchfile:
                    if Prod_Code in line:
                        print(line)
                        receipt = open('Receipt.txt', 'w')
                        receipt.write(line, \n)
                        receipt.close()
                        break

        else:
            print("incorrect length, try again")

    except ValueError:
        if Prod_Code == "Done":
            print("Your receipt is being calculated")
            exit()

        else:
             print("you must enter an integer")

print
不同,
write
只接受一个参数(此外,如果不将浮点和整数转换为字符串,则无法写入浮点和整数-这不是问题所在)

当然,您的
\n
字符必须被引用。所以写下:

receipt.write(line + "\n")
在您的评论之后,您的代码似乎无法按预期工作,即使在进行此修复之后也是如此,因为您只编写了一行(无附加),并且在匹配了一行后就中断了循环:只编写一行的两个原因。我提出以下修正:

receipt = None

with open('Data Base.txt', 'r') as searchfile:
    for line in searchfile:
        if Prod_Code in line:
            print(line)
            if receipt == None:
                receipt = open('Receipt.txt', 'w')
            receipt.write(line+"\n")

if receipt != None:
   receipt.close()
仅当存在匹配项时才会创建输出文件。它在循环期间保持打开状态,因此会追加行。最后,如果需要,它会关闭文件


请注意,如果多次执行该操作,这种线性搜索不是最优的。最好将文件内容存储在
列表中
,然后在行上迭代。但那是另一个故事…

“\n”
,改为a+,因此
行+“\n”
它必须是
”\n'
这解决了问题,但是程序仍然每次写入同一行,并且不启动新行。有没有办法解决这个问题?@joewalley
receipt=open('receipt.txt','w')
每次都以写入模式打开文件,因此将覆盖以前的数据并重新开始。啊,好的,谢谢。现在一切正常。@joewalley你确定吗?因为有一个
中断
,它也阻止写入超过一行。嗯,我已经编辑了我的帖子(但没有测试它,因为我现在不确定你期望的是什么),中断是用来中断第二个while True循环的,因此可以输入另一个数字,然后这些数字对应于数据库文本文件中的一行。然后,程序将该行写入收据文本文件,并中断循环,将其返回顶部,这意味着用户可以输入另一个数字