1、读取指定目录下的所有文件 2、读取指定文件,输出文件内容 3、创建一个文件并保存到指定目录
# -*- coding: UTF-8 -*- ''' 1、读取指定目录下的所有文件 2、读取指定文件,输出文件内容 3、创建一个文件并保存到指定目录 ''' import os import sys import csv #导入csv处理库 import numpy as np import sys # 遍历指定目录,显示目录下的所有文件名 def eachFile(filepath): pathDir = os.listdir(filepath) for allDir in pathDir: child = os.path.join('%s%s' % (filepath, allDir)) #print (child) # .decode('gbk')是解决中文显示乱码问题 file_name=child readFile(file_name) # 读取文件内容并打印 def readFile(filename): result.writerow(['name',filename]) # 将文件名写入csv文件 with open(filename,'r')as fp: while True: # 循环读取 temp = fp.readline() if len(temp) == 0: break else: temp_list = list(temp.split()) #print (temp_list) result.writerow(temp_list) #result.writerow(temp_list) #headers=['name','sign', 'v'] f1 = open('quan.csv', 'w',newline='') # 打开根目录下的result.csv,你首先要打开excel新建一个空的.csv文件并命名为result result = csv.writer(f1) #result.writeheader() filePath = r"E:/yanlifei/weather/progrem/result_hail2/" eachFile(filePath)