Python 3,方法open()、read()和write()

Python 3,方法open()、read()和write(),python,file,writing,Python,File,Writing,当我运行脚本时,编译器的行为就像没有打印(target.read())行一样。如果我在该行之前关闭target,并创建新变量,比如说txt=open(filename,'r+'),然后打印(txt.read()),它就会工作。有人能解释一下为什么它不能像我上面所说的那样工作吗?将处理文件视为有两个指针,一个是文件本身的变量,另一个是指向当前文件位置的指针 首先target.truncate文件以清空内容,指针位于文件中的第一个字符处 然后给出3个target.write命令,当该命令完成时,指针

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

将处理文件视为有两个指针,一个是文件本身的变量,另一个是指向当前文件位置的指针

首先
target.truncate
文件以清空内容,指针位于文件中的第一个字符处

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


最后,尝试一个
目标。读取
。此时,光标位于文件的末尾,从该点开始向前移动,没有任何内容可读取。如果要读取文件的内容,则需要关闭并重新打开文件,或者在实际执行
目标之前,执行一次将指向文件开头的指针移动到第0个字节的操作。读取

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

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()
您可以在read()之前添加这一行,以更改文件中第一个位置的指针

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()

看起来对我有用

target.seek(0)

用open(filename,'w')作为目标:
的形式打开文件,删除任何数据,写两行输入,然后用open(filename,'r')作为目标:
的形式打开并读取,不是更容易吗?起初是这样做的,但后来我改变了代码,试图弄清楚为什么那行不工作,所以每次写入后都会发生这种情况?我的意思是,在我写入文件之后,我应该关闭它并重新打开?理想情况下,您应该保持操作逻辑上的分离。完成逻辑操作后,可以利用该语句自行关闭文件。