Python文件读写测试write,read

版权声明:找不到大腿的时候,让自己变成大腿. https://blog.csdn.net/Xin_101/article/details/86086631

1 open文件操作

open文件操作命令,w模式写入数据时,若文件不存在,则新建文件.

1.0 新建文件及写入数据write

# 新建文件对象f,通过f进行读写操作
# w模式,每次运行程序,文件指针在初始位置
# 数据实时更新,第一次写入的数据会被第二次写入的数据擦除
with open("test.txt", "w") as f:
	# 写入数据:write方法
	f.write("xindaqi")
# a模式
# 写入文件,指针在文件末尾
# 后面写入的数据不会覆盖前面写入的数据
with open("test.txt", "a") as f:
	f.write("xindaqi")

1.2 文件读取read

1.2.1 读取全部数据

  • Demo1
with open("test.txt", 'r') as f:
	lines = f.read()
	print("File data: {}".format(lines))
  • Demo2
with open("test.txt", 'r') as f:
	lines = []
	# readlines()读取文件全部内容
	# 返回一个list
	for line in f.readlines():
		# 去除换行符
		line = line.strip('\n')
		lines.append(line)
		print("File data: {}".format(line))
	while '' in lines:
		# 删除空值
		lines.remove('')
	print("File data: {}".format(lines))
  • Demo3
with open("test.txt", 'r') as f:
	lines = []
	while True:
		line = f.readline().strip('\n')
		lines.append(line)
		if not line:
			break
	while '' in lines:
		lines.remove('')
	print("File data: {}".format(lines))
		

1.2.2 读取文件的一行

with open("test.txt", 'r') as f:
	# 读取文件的一行
	# 返回字符串str
	line = f.readline()
	print("File data: {}".format(line))

2 os文件操作

2.1 创建空文件

import os
os.mknod("test.txt")

2.2 判断文件夹新建及新建

import os
# 文件夹
dir = "xdq"
# 多级目录
dirs = "/xdq/x"
# 判断xdq文件夹是否存在
if not os.path.exists(dir):
	# xdq文件夹不存在,则新建文件夹
	os.mkdir(dir)
if not os.path.exists(dirs):
	os.makedirs(dirs)

2.3 判断文件存在及新建

import os
file = 'xdq.txt'
# 判断文件是否存在
if not os.path.exists(file):
	# 文件不存在,使用touch新建文件
	os.system(r'touch {}'.format(file))

3 总结

  • 操作文件是数据处理的基础;
  • 文件读取需要注意空值和换行符号的处理;
  • 自动新建文件及判断文件是否存在再创建;

[参考文献]
[1]https://www.cnblogs.com/juandx/p/4962089.html
[2]https://blog.csdn.net/u013247765/article/details/79050947
[3]http://blog.51cto.com/steed/1977225
[4]https://www.cnblogs.com/MisterZhang/p/9134709.html


猜你喜欢

转载自blog.csdn.net/Xin_101/article/details/86086631
今日推荐