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

时间:2018-10-11 17:05:44

标签: python file writing

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.read())行。如果我在该行之前关闭目标,然后像说txt = open(filename,'r +')那样创建新变量,然后打印(txt.read()),它将起作用。有人可以解释为什么它不能像我上面那样工作吗?

3 个答案:

答案 0 :(得分:1)

认为使用文件有两个指针,一个是文件本身的变量,第二个是指向文件当前位置的指针。

您首先onLoad: function(){current.iframeLoaded(this);}} 将文件清空内容,指针位于文件的第一个字符。

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

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

答案 1 :(得分:0)

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

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

target.seek(0)

答案 2 :(得分:0)

看起来对我有用。

for i in value['result']:
    print('POSTCODE: {} England REGION: {}'.format(i['postcode'], i['region']))

POSTCODE: CB3 0FA England REGION: East of England
POSTCODE: CB3 0GT England REGION: East of England
POSTCODE: CB3 0FT England REGION: East of England
相关问题