import numpy as npimport pandas as pdimport os import csvpath = '/Users/wwl/Downloads/sample'# 每行每行地处理def txt2csv_Row(): for file in os.listdir(path): # path内部有一个文件夹,需要跳过这个文件夹 if(file[-3:] == 'txt'): # 拼接目录地址 fromFile = path +'/'+ file print(fromFile) toFile = path + '/csvFile/' + file[:-3]+ 'csv' # 按行转换 csvfile = open(toFile, 'w+') lines = open(fromFile, 'r', encoding='utf-8').readlines() for line in lines: csvfile.write(line) csvfile.close()# 借助Numpy来处理,遇到文件中有空值会报错。def txt2csv_Numpy(): countSucc = 0 countFailed = 0 for file in os.listdir(path): filepath = path +'/'+file try : data_txt = np.loadtxt(filepath.strip()) data_txtDF = pd.Dataframe(data_txt) data_txtDF.to_csv(path + '/csvFile/' + file[:-3]+ 'csv',index=False) countSucc = countSucc + 1 except Exception: print(filepath) countFailed = countFailed + 1 continue print("succ" + str(countSucc)) print("failed" + str(countFailed))# text()