1. Read all files in the specified directory 2. Read the specified file and output the content of the file 3. Create a file and save it to the specified directory
# -*- coding: UTF-8 -*- ''' 1. Read all files in the specified directory 2. Read the specified file and output the content of the file 3. Create a file and save it to the specified directory ''' import them import sys import csv #Import csv processing library import numpy as np import sys # Traverse the specified directory and display all file names in the directory def eachFile(filepath): pathDir = os.listdir(filepath) for allDir in pathDir: child = os.path.join('%s%s' % (filepath, allDir)) #print (child) # .decode('gbk') is to solve the problem of Chinese display garbled characters file_name=child readFile(file_name) # read the contents of the file and print def readFile(filename): result.writerow(['name',filename]) # Write the filename to the csv file with open(filename,'r')as fp: while True: # loop read 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='') # Open result.csv in the root directory, you first need to open excel and create an empty .csv file and name it result result = csv.writer(f1) #result.writeheader() filePath = r"E:/yanlifei/weather/progrem/result_hail2/" eachFile(filePath)