将txt文件批处理转换为csv文件

convert_txt_to_csv(txt_path, csv_path):
        """Convert the txt file to csv file"""
        #list to store the filenames and the path
        data = list_files(path=txt_path)
        csv_data=[] #list to store the csv files

        os.makedirs(csv_path) if not os.path.exists(csv_path) else print('CSV folder existd')
        for month in range(12):
            if next(walk(csv_path))[1].__len__()==12:
                print('Folders exist')
                break
            print('Creating subdirectories')

            os.makedirs(os.path.join(next(walk(csv_path))[0],'0'+str(month+1) if month<9 else str(month+1)))

        for index in range(len(data)):
            '''Store csv filename to <csv_data> list'''
            csv_data.append(os.path.join(csv_path, data[index], split(csv_path)[1].replace('txt','csv')))

        for index in range(len(data)):
            ''' reading the text files, and convert it to csv'''
            try:
                print('Processing:{}'.format(data[index])
                int_csv = csv.reader(open[data[index],'r'),delimiter='\t')
                out_csv = csv.writer(open(csv_data[index], 'x'))
                out_csv.writerow(in_csv)
            except FileNotFoundError:
                print('File not Found: {}'.format(data[index]))


猜你喜欢

转载自blog.csdn.net/bill_zhang5/article/details/79038817