python中关于txt文件的处理(读取、写入、csv文件转为txt)

一、读取txt文件: numpy.loadtxt() 用法

  • 基本语法
np.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

其中

字段作用
npimport 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 = Nonenone使用全部列(默认使用全部列),
usecols = (0,2)表示只使用0列和2列,列号从0开始
unpack = FalseFalse把所有列合并输出,
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)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值