Python 为什么这种分裂不起作用?

Python 为什么这种分裂不起作用?,python,text-files,Python,Text Files,为什么这种分裂不起作用?当我运行代码时,不会打印split_1 with open ('r_3exp', 'a+') as file_1: choice = input ('1 (write) or 2? ') number = input ('What number?') if choice == '1': file_1.write ('\n') file_1.write ('Here are some numbers : 1233 8989' + ' ' + num

为什么这种分裂不起作用?当我运行代码时,不会打印
split_1

with open ('r_3exp', 'a+') as file_1:
 choice = input ('1 (write) or 2? ')
 number = input ('What number?')

 if choice == '1':
    file_1.write ('\n') 
    file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
 else:
    for line in file_1:
        split_1 = line.split (":")
        print (split_1)

这是因为您正在以
a+
模式打开文件

a+
允许读取和追加文件。表面上看,这听起来很适合你想要的东西。但是,对于这种模式,您忽略了一些微妙的技巧:

  • 。换句话说,您不再从文件的开头开始读取,而是从文件的末尾开始读取

  • 因此,当您对文件_1中的行执行
    操作时,实际上是从文件末尾的字符开始读取。因为根据定义,这里什么都没有,
    line
    返回一个空字符串,并且
    line.split(“:”)
    也是空的

要纠正这一点,更谨慎的做法是稍微重新组织代码,使用
r
模式或
a
模式:

choice = input("1 (write) or 2? ")
if choice == "1":
    number = input("What number? ")
    with open("r_3exp","a") as file_1:
        file_1.write ('\n') 
        file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
elif choice == "2":
    with open("r_3exp","r") as file_1:
        for line in file_1:
            split_1 = line.split (":")
            print (split_1)
r
打开文件,从文件的第一个字符开始读取,而不是从最后一个字符开始读取



我仍然建议使用Python2.7的人使用上述代码,但还有一个额外的警告:
input()
在Python2.7中返回
None
,因为它实际上是将输入作为Python命令进行评估。Python2.7中使用的正确函数是
raw\u input()
,它正确地返回字符串。

这是因为您是在
a+
模式下打开文件的

a+
允许读取和追加文件。表面上看,这听起来很适合你想要的东西。但是,对于这种模式,您忽略了一些微妙的技巧:

  • 。换句话说,您不再从文件的开头开始读取,而是从文件的末尾开始读取

  • 因此,当您对文件_1中的行执行
    操作时,实际上是从文件末尾的字符开始读取。因为根据定义,这里什么都没有,
    line
    返回一个空字符串,并且
    line.split(“:”)
    也是空的

要纠正这一点,更谨慎的做法是稍微重新组织代码,使用
r
模式或
a
模式:

choice = input("1 (write) or 2? ")
if choice == "1":
    number = input("What number? ")
    with open("r_3exp","a") as file_1:
        file_1.write ('\n') 
        file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
elif choice == "2":
    with open("r_3exp","r") as file_1:
        for line in file_1:
            split_1 = line.split (":")
            print (split_1)
r
打开文件,从文件的第一个字符开始读取,而不是从最后一个字符开始读取



我仍然建议使用Python2.7的人使用上述代码,但还有一个额外的警告:
input()
在Python2.7中返回
None
,因为它实际上是将输入作为Python命令进行评估。Python2.7中使用的正确函数是
raw\u input()
,它正确地返回字符串。

您使用的是Python3还是2.7?到目前为止,它不起作用的原因(在Python2.7中)是因为没有向文件
r\u 3exp
写入任何内容,这与
input()
将用户输入评估为有效的Python,而
raw\u input()
返回字符串有关。Python3以及1已经被选中,这意味着文件已写入。您使用的是Python 3还是2.7?到目前为止,它不起作用的原因(在Python2.7中)是因为没有向文件
r\u 3exp
写入任何内容,这与
input()
将用户输入评估为有效的Python,而
raw\u input()
返回字符串有关。Python3以及1已经被选中,意味着该文件已写入。