python3 basics-files

Procedure 1

#!/usr/bin/python3
f = open("平凡的路.txt",encoding="utf-8")
data = f.read()
data2 = f.read()
print(data)
print("data2",data2)

Procedure 1 execution result

Procedure 1 analysis:

The result of the second reading of data2 is empty. The reason is: when the first reading operation is completed, the file cursor is at the end of the file; then the reading operation continues, the system reads backward from the cursor, but the cursor is At the end, so the read content is empty.

Procedure 2

The tell()  method returns the current position of the file, that is, the current position of the file pointer.

The tell() method syntax is as follows:

fileObject.tell()

The seek()  method is used to move the file reading pointer to the specified position.

The seek() method syntax is as follows:

fileObject.seek(offset[, whence])

The flush()  method is used to flush the buffer, that is, the data in the buffer is written to the file immediately, and the buffer is cleared at the same time. There is no need to passively wait for the output buffer to be written.

Under normal circumstances, the buffer is automatically refreshed after the file is closed, but sometimes you need to refresh it before closing, then you can use the flush() method.

The flush() method syntax is as follows:

fileObject.flush();

The content of the file ordinary road.txt is as follows:

徘徊着的 在路上的
你要走吗 via via
易碎的 骄傲着
那也曾是我的模样
沸腾着的 不安着的
你要去哪 via via
谜一样的 沉默着的
故事你真的 在听吗
#!/usr/bin/python3
data = open("平凡的路.txt",encoding="utf-8")
print(data.tell())
print(data.readline())
print(data.tell())
data.seek(0)
print(data.tell())
print(data.readline())
print(data.tell())
#encoding打印字符集
print(data.encoding)
#flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
#一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
print(data.flush())

Program 3 progress bar

#!/usr/bin/python3
import sys,time
count=0
for i in range(10):
    sys.stdout.write("# %s" %count)
    count=count+1
    sys.stdout.flush()
    time.sleep(1)

Guess you like

Origin blog.csdn.net/jundao1997/article/details/106524743