Python编程-python中的文件操作,open,read,write,close,seek

一定要记得调用close,来关闭文件。 -----箴言-----

1. 内容简介:

和其它语言一样,python也支持文件操作。

本例子展示了文件的基本操作:

打开,关闭,读写,更名,文件内容定位。

2.代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

import os

#open close
def test_open():
	#open
	f = open ("hello.txt",'r')
	print('file name:' + f.name)
	print('file mode:' + f.mode)
	is_closed = f.closed
	print('file closed:') #文件是否已经处于关闭状态
	print(is_closed)
	print('\n\n')

	#close
	f.close() 

#read write
def test_write():
	#open
	f = open ("hello.txt",'a+')
	f.write('hello python!!!\n')
	f.write('hello 2020!!!')

    #seek,改变当前文件的位置到文件开头
	f.seek(0,0)   
	read_str=f.read(100)
	print('read_str:')
	print(read_str)

	f.close()

#main
if __name__ == '__main__':
	test_open()
	test_write()

	#rename: 从hello.txt变为hi.txt
	os.rename('hello.txt','hi.txt')

在文件操作完成后,一定要close。

运行结果:

扫描二维码关注公众号,回复: 12924784 查看本文章

先保证在python脚本同目录下有hello.txt文件存在。

aaaaa:file_test user1$ python3 file_test1.py 

file name:hello.txt

file mode:r

file closed:

False

read_str:

hello

hello python!!!

hello 2020!!!hello python!!!

hello 2020!!!hello python!!!

hello 2020!!!hello p

aaaaa:file_test user1$ ls

file_test1.py hi.txt

猜你喜欢

转载自blog.csdn.net/liranke/article/details/114144407