一、读取txt文件: numpy.loadtxt() 用法
- 基本语法
np.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
其中
字段 | 作用 |
---|---|
np | import numpy as np |
fname | 文件路径/文件名 |
dtype = | int 数据类型设置为整形 |
comments = ‘#’ | 跳过行数据开头为#的行 |
delimiter = None | 加载文件分隔符 |
converters = None | converters={0:add_one} 表示对第0列使用add_one函数,add_one函数需另行定义 |
skiprows = n | 跳过前n行,行号从1开始 |
usecols = None | none使用全部列(默认使用全部列), usecols = (0,2)表示只使用0列和2列,列号从0开始 |
unpack = False | False把所有列合并输出, True把每列看作一个向量,单独输出 |
ndmin=0 |
- 应用案例
#数据准备 test20220117.txt
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
代码及输出结果
- 输入1:
np.load()
直接加载
import numpy as np
a = np.loadtxt('E:/tests/2022-01/test20220117.txt')
print(a)
#执行结果为
[[1.00 2.00 3.00 4.00]
[2.00 3.00 4.00 5.00]
[3.00 4.00 5.00 6.00]
[4.00 5.00 6.00 7.00]]
- 输入2:添加
dtype = int
参数
a = np.loadtxt('E:/tests/2022-01/test20220117.txt',dtype = int)
print(a)
#执行结果为
[[1 2 3 4]
[2 3 4 5]
[3 4 5 6]
[4 5 6 7]]
- 输出3:添加
skiprows=1
参数
a = np.loadtxt('E:/tests/2022-01/test20220117.txt', dtype=int, skiprows=1)
print(a)
#执行结果为
[[2 3 4 5]
[3 4 5 6]
[4 5 6 7]]
- 输出4:添加
usecols=(0, 2)
参数
a = np.loadtxt('E:/tests/2022-01/test20220117.txt', usecols=(0, 2))
print (a)
#执行结果为
[[1.00 3.00]
[2.00 4.00]
[3.00 5.00]
[4.00 6.00]]
- 输出5:添加
converters={0:add_one}
参数
def add_one(x):
return int(x)+1
a = np.loadtxt('E:/tests/2022-01/test20220117.txt', dtype=int, usecols=(0, 2),converters={0:add_one})
print (a)
#执行结果为
[[2 3]
[3 4]
[4 5]
[5 6]]
- 输出6:添加
unpack = True
参数
def add_one(x):
return int(x)+1
a = np.loadtxt('E:/tests/2022-01/test20220117.txt', dtype=int, usecols=(0, 2),converters={0:add_one}, unpack = True)
print (a)
#执行结果为
[[2 3 4 5]
[3 4 5 6]]
二、用open打开txt文件
直接使用open()
file = open('E:/tests/2022-01/test20220119.txt','w')
file.write('hello world!')
注:
参数中w
表示:当该文件存在时,直接执行下一步写入操作;当文件不存在时,先创建文件
定义函数套用open()
def text_create(name, msg):
text_path = 'E:/tests/2022-01/'
full_path = text_path + name + '.txt'
file = open(full_path,'w')
file.write(msg)
file.close()
print('Done')
text_create('hello','hello world')
三、txt首行追加信息
import os
def change_one(file_name):
with open(file_path+file_name, 'r+') as f:
content = f.read()
f.seek(0, 0)
txt_add = ['序号','列名1']
txt_add = str ('\t'.join(txt_add))
f.write(txt_add+'\n'+content)
def change_all(file_path):
listdir = os.listdir(file_path)
for f in listdir:
change_one(f)
file_name = 'test1.txt'
file_path = 'E:/Test/'
change_all(file_path)
四、python读取csv文件转换成txt
import pandas as pd
import os
# 打开文件csv,转换一个文件
def change_one(file_name):
(shotname,extension) = os.path.splitext(file_name)
data = pd.read_csv(file_path+file_name, encoding='utf-8')
with open(file_path+shotname+'.txt','a+', encoding='utf-8',) as f:
for line in data.values:
f.write((str(line[0])+'\t'+str(line[1])+\n'))
#批量化
def change_all(file_path):
listdir = os.listdir(file_path)
for f in listdir:
change_one(f)
file_name = 'test1.csv'
file_path = 'E:/Test/'
change_all(file_path)