当前位置: 首页 > 后端技术 > Python

Python读写txt

时间:2023-03-26 11:16:30 Python

原文链接使用pandas.read_csv进行读写操作,使用data.to_csv进行写操作。importnumpyimportpandasaspd#readdata=pd.read_csv(r"/home/snowstorm/mmdetection/data/groundtruth.txt",header=None)#readTXT:以逗号分隔#data=pd.read_csv(r"/home/snowstorm/mmdetection/data/groundtruth.txt",header=None,sep='')#ReadTXT:空格分隔print(data)#writedata.to_csv("/home/snowstorm/mmdetection/data/write.txt",sep=',',header=False,index=False)指定要读写的行和列importnumpy#readdatadefloadDatadet(infile,k):f=open(infile,'r')sourceInLine=f.readlines()dataset=[]forlineinsourceInLine:#读取数据temp1=line.strip('\n')temp2=temp1.split('\t')dataset.append(temp2)foriinrange(0,len(dataset)):#Converttoanintegerforjinrange(k):dataset[i].append(int(dataset[i][j]))del(dataset[i][0:k])list=sum(dataset,[])#转为一维数组posit_data=numpy.array(list).reshape(len(list)//4,4)#转为n*的二维数组4返回posit_data#写入数据defWritedata(negat_data):filename='C:\\Users\\DZF\\Desktop\\negative.txt'#要写入的文件row=numpy.array(negat_data).shape[0]#获取Numberoflinesnwithopen(filename,'w')asf:#如果filename不存在,会自动创建,写入前清空文件foriinrange(0,row):f.write(str(negat_data[i][0:12]))f.write("\n")infile='C:\\Users\\snow\\Desktop\\positive.txt'#要读取的文件k=1#Columnsposit_data=loadDatadet(infile,k)Writedata(posit_data)print(posit_data)了解更多编程知识,请关注我的公众号:代码之道