【问题标题】:Python 3, methods open(), read(), and write()Python 3,方法 open()、read() 和 write()
【发布时间】:2025-12-03 17:25:01
【问题描述】:
from sys import argv

script, filename = argv

print ("We're going to erase %r" % filename)
print ("If you don't want to do that, press CTRL-C (^C)")
print ("If you do want that, hit RETURN.")

input("?")

print ("Opening the file...")
target = open(filename, 'r+')

print ("Truncating the file. Goodbye!")
target.truncate()

print ("Enter two lines: ")
line1 = input("Line 1: ")
line2 = input("Line 2: ")

print ("I'm going to write those to the file")

target.write(line1)
target.write('\n')
target.write(line2)

print (target.read()) 

print ("Closing file")
target.close()

当我运行脚本时,编译器就像没有 print (target.read()) 行一样。如果我在该行之前关闭目标,并创建新变量,比如让我们说 txt = open(filename, 'r+') 然后 print (txt.read()) 它可以工作。有人能解释一下为什么它不像我上面那样工作吗?

【问题讨论】:

  • with open(filename, 'w') as target: 的身份打开文件会擦除任何数据,写入两个输入行,然后with open(filename, 'r') as target: 并读取,这不是更容易吗?
  • 一开始是这样做的,但后来我正在更改代码以试图找出该行不起作用的原因

标签: python file writing


【解决方案1】:

将文件视为具有 2 个指针,一个是文件本身的变量,第二个是指向您当前所在文件位置的指针。

你先target.truncate文件清空内容,指针在文件的第一个字符处。

然后你给出 3 个target.write 命令,当该命令完成时,指针将移动到每行的末尾。

最后,您尝试target.read。此时光标位于文件末尾,从该点开始没有可读取的内容,向前移动。如果要读取文件的内容,则需要关闭并重新打开文件,或者在实际执行 @987654327 之前执行 target.seek(0) 将指向文件开头的指针移动到第 0 个字节@。

【讨论】:

  • 所以每次写作后都会发生这种情况?我的意思是,在我写入文件后,我应该关闭它并重新打开它?
  • 理想情况下,您应该保持操作在逻辑上分离。完成逻辑操作后,您可以使用 with 语句自行关闭文件。
【解决方案2】:

当您在文件中写入和读取某些内容时,您会更改文件指针。在这种情况下,您正在读取文件中的最后一个位置。

您可以在 read() 之前添加此行,以更改文件中第一个位置的指针。

target.seek(0)

【讨论】:

    【解决方案3】:

    看起来它对我有用。

    from sys import argv
    
    script, filename = argv
    
    print ("We're going to erase %r" % filename)
    print ("If you don't want to do that, press CTRL-C (^C)")
    print ("If you do want that, hit RETURN.")
    
    input("?")
    
    print ("Opening the file...")
    with open(filename, 'w') as target:
      print ("Enter two lines: ")
      line1 = input("Line 1: ")
      line2 = input("Line 2: ")
      print ("I'm going to write those to the file")
      target.write(line1)
      target.write('\n')
      target.write(line2)
    
    with open(filename, 'r') as target:
      print (target.read())
    
    input ("Closing file")
    

    【讨论】: