简体   繁体   English

Python基础知识 - 为什么不是我的文件打印的内容?

[英]Python basics- why aren't the contents of my file printing?

I'm running this from eclipse, the file name I'm working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the "print txt.read()" doesn't seem to do anything (prints a blank line), see the output after the code: 我是从eclipse运行的,我正在使用的文件名是ex16_text.txt(是的我输入正确。它正确地写入文件(输入出现),但是“print txt.read()”似乎没有做任何事情(打印一个空行),看到代码后的输出:

filename = raw_input("What's the file name we'll be working with?")

print "we're going to erase %s" % filename

print "opening the file"
target = open(filename, 'w')

print "erasing the file"
target.truncate()

print "give me 3 lines to replace file contents:"

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "writing lines to file"

target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)

#file read
txt = open(filename)

print "here are the contents of the %s file:" % filename
print txt.read()

target.close()

Output: 输出:

What's the file name we'll be working with?ex16_text.txt we're going to erase ex16_text.txt opening the file erasing the file give me 3 lines to replace file contents: line 1: three line 2: two line 3: one writing lines to file here are the contents of the ex16_text.txt file: 我们将使用的文件名是什么?ex16_text.txt我们要擦除ex16_text.txt打开文件擦除文件给我3行替换文件内容:第1行:第3行:第2行:第3行:在这里写行文件是ex16_text.txt文件的内容:

You should flush the file after you have written to it to ensure that the bytes have been written. 您应该在写入文件后刷新文件以确保已写入字节。 Also read the warning: 另请阅读警告:

Note: flush() does not necessarily write the file's data to disk. 注意:flush()不一定将文件的数据写入磁盘。 Use flush() followed by os.fsync() to ensure this behavior. 使用flush()后跟os.fsync()来确保此行为。

You should also close the file if you have finished writing to it and want to open it again with read only access. 如果您已完成写入并希望以只读访问权限再次打开该文件,则还应关闭该文件。 Note that closing the file also flushes - if you close it then you don't need to flush first. 请注意,关闭文件也会刷新 - 如果关闭它,则不需要先刷新。

In Python 2.6 or newer you can use the with statement to automatically close the file: 在Python 2.6或更高版本中,您可以使用with语句自动关闭文件:

with open(filename, 'w') as target:
    target.write('foo')
    # etc...

# The file is closed when the control flow leaves the "with" block

with open(filename, 'r') as txt:
    print txt.read()
target.write(line2+"\n")
target.write(line3)
target.close() #<------- You need to close the file when you're done writing.
#file read
txt = open(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM