写一个python脚本,读取csv文件的第二列以逗分割,第二列为时间戳再按照第二列数据排序
时间: 2024-04-12 09:30:46 浏览: 24
当然可以!以下是一个示例脚本,它可以读取一个CSV文件的第二列,并按照第二列的时间戳对数据进行排序:
```python
import csv
def sort_csv_by_timestamp(csv_file):
with open(csv_file, 'r') as file:
reader = csv.reader(file)
header = next(reader) # 读取表头
# 获取第二列数据
data = [(row[1], row) for row in reader]
# 按照第二列的时间戳进行排序
sorted_data = sorted(data, key=lambda x: x[0])
# 将排序后的数据写入新的CSV文件
sorted_csv_file = 'sorted_' + csv_file
with open(sorted_csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(header)
for _, row in sorted_data:
writer.writerow(row)
print(f"排序后的CSV文件已保存为 '{sorted_csv_file}'")
# 使用示例
csv_file = 'data.csv' # 替换为你的CSV文件路径
sort_csv_by_timestamp(csv_file)
```
请将代码中的 `'data.csv'` 替换为你要读取的CSV文件路径,并运行脚本。排序后的数据将保存在名为 `'sorted_data.csv'` 的新CSV文件中。