python 读写文件的推荐方法
写在前面
python读取文件有多种方法,本文只针对python读一个文件、多个文件和写文件三种情况,分别给出一种推荐方法,文件为TXT格式。其他情况方法大同小异,大家可带关键字搜索。如果有更好的方法或是错误,请大家在评论指出,菜鸟博主求大家带。
python读一个文件:numpy.loadtxt
程序示例
import numpy as np
f1=np.loadtxt('num_test.txt',dtype=float)
f2=np.loadtxt('num_test.txt',dtype=int)
f3=np.loadtxt('string_test.txt',dtype=str)
print("f1\n",f1)
print("f2\n",f2)
print("f3\n",f3)
运行示例
文件存储示例
上图为:num_test.txt
上图为:string_test.txt
python读多个文件:glob.glob
通配符
- 代替一个或多个字母:*
- 代替一个字母:?
- 表示范围[]
程序示例
import glob
files1=glob.glob('*.txt') #读取全部txt文件
files2=glob.glob('?test.txt')
files3=glob.glob('[1-3]_test.txt')
print("files1:",files1)
print("files2:",files2)
print("files3:",files3)
print("file in files3")
for f3 in files3: #用循环处理读取的单个文件
print(f3) #此处可替换为响应的文件操作
运行结果
文件存储示例
python 写文件:numpy.savetxt
程序示例
import numpy as np
l=np.arange(0,12).reshape(3,4)
np.savetxt("save.txt",l,fmt="%d")