Chuyển đổi tất cả các tệp CSV trong một thư mục thành xlsx Python

Làm xong mình đã có công thức để nhắn tin vào cột dựa trên từng loại bản ghi cố định chiều rộng cột đếm

Mọi ID sẽ có RecordType1 và có thể có thêm các hàng RecordType2 và RecordType3. Giả sử có 500 ID duy nhất [recordtype1], tổng số 900 Bản ghi [400 hàng dữ liệu bổ sung cho RecordType2 & 3]

Ví dụ.
HeaderRecord DateDateHourDate L
RecordType1 First Last ID01 TitleDate1Date2 zerofilldate3
RecordType2 ID01 Date1Date2 YesNo Spacefill
RecordType3 ID01 DataInfoDate1 ZerofillDate
RecordType1 First Last ID02 TitleDate1Date2 zerofilldate3
RecordType2 ID02 Date1Date2 YesNo Spacefill
RecordType3 ID01 DataInfoDate1 ZerofillDate
RecordType1 First Last ID03 TitleDate1Date2 zerofilldate3
RecordType2 ID03 Date1Date2 YesNo Spacefill
RecordType3 ID03 DataInfoDate1 ZerofillDate
TrailerRecord Count

Đáp lại

Các hàm read_* được sử dụng để đọc dữ liệu cho gấu trúc, các phương thức to_* được sử dụng để lưu trữ dữ liệu. Phương thức to_excel[] lưu trữ dữ liệu dưới dạng tệp excel. Trong ví dụ ở đây, sheet_name được đặt tên là hành khách thay vì Sheet1 mặc định. Bằng cách đặt chỉ mục=Sai, nhãn chỉ mục hàng không được lưu trong bảng tính

Tôi đang làm việc với kịch bản này trước tiên sẽ lấy tất cả. csv và chuyển đổi chúng. xlsx trong một thư mục riêng biệt. Tôi nhận được tệp đầu tiên để xuất ra chính xác cách tôi muốn trong thư mục 'Tệp tập lệnh', nhưng sau đó, nó đưa ra lỗi Traceback trước khi nó thực hiện lỗi thứ hai

Mã tập lệnh bên dưới, lỗi Tracback bên dưới. Một số dữ liệu đường dẫn bị xóa để bảo mật

import pandas as pd
import matplotlib.pyplot as plt
import os

# Assign current directory and list files there
f_path = os.path.dirname[__file__]
rd_path = f_path+'\\Raw Data'
sc_path = f_path+'\\Script files'

# Create /Script files folder

if os.path.isdir[sc_path] == False:
    os.mkdir[sc_path]
    print["\nCreating new Script files path here...",sc_path]
else:
    print["\nScript files directory exists!"]

# List files in Raw Data directory
print["\nRaw Data files in the directory:\n",rd_path,"\n"]

for filename in os.listdir[rd_path]:
    f = os.path.join[rd_path,filename]
    if os.path.isfile[f]:
        print[filename]
print["\n\n\n"]

# Copy and edit data files to /Script files folder
for filename in os.listdir[rd_path]:
    src = os.path.join[rd_path,filename]
    if os.path.isfile[src]:
        name = os.path.splitext[filename][0]
        read_file = pd.read_csv[src]
        result = sc_path+"\\"+name+'.xlsx'
        read_file.to_excel[result]
        print[src,"\nconverted and written to: \n",result,"\n\n"]
Traceback [most recent call last]:
  File "C:\Users\_________________\Graph.py", line 32, in 
    read_file = pd.read_csv[src]
  File "C:\Users\_____________\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func[*args, **kwargs]
  File "C:\Users\______________\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
    return _read[filepath_or_buffer, kwds]
  File "C:\Users\_____________\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 581, in _read
    return parser.read[nrows]
  File "C:\Users\_____________\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 1250, in read
    index, columns, col_dict = self._engine.read[nrows]
  File "C:\Users\_____________\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 225, in read
    chunks = self._reader.read_low_memory[nrows]
  File "pandas\_libs\parsers.pyx", line 805, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 861, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 847, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1960, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 47, saw 8

Trong hướng dẫn nhanh này, bạn sẽ thấy các bước hoàn chỉnh để chuyển đổi tệp CSV thành tệp Excel bằng Python

Để bắt đầu, đây là một mẫu đơn giản mà bạn có thể sử dụng để chuyển đổi CSV sang Excel bằng Python

import pandas as pd

read_file = pd.read_csv [r'Path where the CSV file is stored\File name.csv']
read_file.to_excel [r'Path to store the Excel file\File name.xlsx', index = None, header=True]

Trong phần tiếp theo, bạn sẽ thấy cách áp dụng mẫu này vào thực tế

Các bước để chuyển đổi CSV sang Excel bằng Python

Bước 1. Cài đặt gói Pandas

Nếu bạn chưa làm như vậy, hãy cài đặt gói Pandas. Bạn có thể sử dụng lệnh sau để cài đặt gói Pandas [trong Windows]

pip install pandas

Bước 2. Chụp đường dẫn lưu trữ tệp CSV

Tiếp theo, chụp lại đường dẫn nơi tệp CSV được lưu trữ trên máy tính của bạn

Dưới đây là một ví dụ về đường dẫn lưu trữ tệp CSV

C. \Users\Ron\Desktop\Test\Product_List. csv

Trong đó ‘Product_List‘ là tên tệp CSV hiện tại và ‘csv‘ là phần mở rộng của tệp

Bước 3. Chỉ định đường dẫn nơi tệp Excel mới sẽ được lưu trữ

Bây giờ, bạn sẽ cần chỉ định đường dẫn nơi tệp Excel mới sẽ được lưu trữ. Ví dụ

C. \Users\Ron\Desktop\Test\New_Products. xlsx

Trong đó ‘New_Products‘ là tên tệp mới và ‘xlsx‘ là phần mở rộng tệp Excel

Bước 4. Chuyển đổi CSV sang Excel bằng Python

Đối với bước cuối cùng này, bạn sẽ cần sử dụng mẫu sau để thực hiện chuyển đổi

import pandas as pd

read_file = pd.read_csv [r'Path where the CSV file is stored\File name.csv']
read_file.to_excel [r'Path to store the Excel file\File name.xlsx', index = None, header=True]

Đây là cú pháp hoàn chỉnh cho ví dụ của chúng tôi [lưu ý rằng bạn sẽ cần sửa đổi đường dẫn để phản ánh vị trí nơi các tệp sẽ .

import pandas as pd

read_file = pd.read_csv [r'C:\Users\Ron\Desktop\Test\Product_List.csv']
read_file.to_excel [r'C:\Users\Ron\Desktop\Test\New_Products.xlsx', index = None, header=True]

Chạy mã bằng Python và tệp Excel mới [i. e. , New_Products] sẽ được lưu tại vị trí được chỉ định của bạn

Chủ Đề