我有多個不同名稱的 .csv 檔案,例如 ATUL.csv、ISEC.csv、XYZ.csv 等……每個檔案都有下面提到的類似資料格式:
datetime symbol open high low close volume
2005-03-10 09:15:00 NSE:ATUL 85.59 89.00 85.19 86.84 73582
2005-03-11 09:15:00 NSE:ATUL 89.44 89.80 85.50 85.94 153945
2005-03-14 09:15:00 NSE:ATUL 86.90 88.75 84.00 84.65 73539
2005-03-15 09:15:00 NSE:ATUL 85.00 85.94 82.00 82.40 79053
我想為每個 .csv 檔案創建一個新的 .txt,格式如下:
- 洗掉“符號”列
- 洗掉標題行,即日期時間|符號|打開.....
- 將“datetime”列日期和時間格式更改為 YYYYMMDD
- 用“;”分隔每一列
下面給出了所需的格式示例以供理解。
20050310;85.59;89.00;85.19;86.84;73582
20050311;89.44;89.80;85.50;85.94;153945
20050314;86.90;88.75;84.00;84.65;73539
20050315;85.00;85.94;82.00;82.40;79053
我正在嘗試下面的代碼來獲取我的輸出
import pandas as pd
data = pd.read_csv('ATUL.csv')
data.drop('symbol', inplace=True, axis=1)
data['datetime'] = pd.to_datetime(data['datetime']).dt.strftime('%Y%m%d')
data.to_csv('output.txt', sep=';', header=None, index=False)
上面的代碼運行良好,但一次創建/轉換一個檔案,我的問題是上面的代碼一次只能轉換一個檔案,我有 500 多個檔案需要每天更新。
有什么方法或代碼可以將我的所有 .csv 檔案轉換為具有所需格式的文本檔案(如上面的代碼所示)
uj5u.com熱心網友回復:
這里的代碼完全符合我在之前評論中的建議。
它利用內置pathlib模塊來簡化處理。
import pandas as pd
from pathlib import Path
def export_csv(input_filepath, output_filepath):
"""Reformat input file and save result to the given output file path."""
data = pd.read_csv(input_filepath)
data.drop('symbol', inplace=True, axis=1)
data['datetime'] = pd.to_datetime(data['datetime']).dt.strftime('%Y%m%d')
data.to_csv(output_filepath, sep=';', header=None, index=False)
folderpath = Path('path/to/csv/files/folder').resolve()
new_suffix = '.txt'
# Convert all .csv files in given folder.
for input_filepath in folderpath.glob('*.csv'):
# Output file path is the same as the input file except it has a different
# extension.
output_filepath = input_filepath.with_suffix(new_suffix)
export_csv(input_filepath, output_filepath) # Convert the file.
uj5u.com熱心網友回復:
我不是 Python 專家,有我的解決方案可以解決您的問題。
首先將所有檔案打包在一個目錄中,然后使用os模塊瀏覽它。
編輯
import os
import pandas as pd
path = "path/to/directory/with/csv"
with os.scandir(path) as it:
for entry in it:
if entry.is_file() and entry.name.endswith(".csv"): # Treat only csv files
# Convert csv to txt with your code here
data = pd.read_csv(entry.name)
data.drop('symbol', inplace=True, axis=1)
data['datetime'] = pd.to_datetime(data['datetime']).dt.strftime('%Y%m%d')
data.to_csv('output.txt', sep=';', header=None, index=False)
如果將路徑值替換為計算機上檔案的實際目錄路徑,這應該可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475889.html
