import csv
# 读取CSV文件并指定编码方式为latin-1
with open('input.csv', 'r', encoding='latin-1') as csv_file:
csv_reader = csv.reader(csv_file)
data = list(csv_reader)
# 确定每列最长的长度
max_lengths = [max(len(row[i]) for row in data) for i in range(len(data[0]))]
# 写入TXT文件并保持对齐
with open('output.txt', 'w', encoding='utf-8') as txt_file:
for row in data:
txt_file.write(' '.join(cell.ljust(max_lengths[i] + 2) for i, cell in enumerate(row)) + '\n')
@echo off
cls
REM 提示用户输入 CSV 档案的完整路径
set /p csv_file=请输入CSV档案的完整路径(例如:C:\path\to\file.csv):
REM 验证输入的 CSV 档案是否存在
if not exist "%csv_file%" (
echo 错误:指定的档案不存在。
pause
exit /b
)
REM 获取 CSV 档案所在的目录路径
for %%F in ("%csv_file%") do (
set "csv_dir=%%~dpF"
)
REM 提示用户输入输出的 TXT 档名
set /p txt_file=请输入输出的TXT档名(例如:output.txt):
REM 构建输出的 TXT 档案的完整路径
set "txt_path=%csv_dir%%txt_file%"
REM 执行命令
type "%csv_file%" | column -t -s "," > "%txt_path%"
echo 操作已完成。结果已储存到 %txt_path%。
pause
import csv
import chardet
def convert_csv_to_txt(input_file, output_file):
# 使用chardet檢測檔案編碼
with open(input_file, 'rb') as f:
rawdata = f.read()
encoding = chardet.detect(rawdata)['encoding']
with open(input_file, 'r', encoding=encoding) as csv_file:
csv_reader = csv.reader(csv_file)
data = list(csv_reader)
# 找到每個欄位的最大寬度
max_lengths = [max(len(row[i]) for row in data) for i in range(len(data[0]))]
with open(output_file, 'w', encoding=encoding) as txt_file:
for row in data:
# 構建每一列的格式化字串,使用固定寬度的空格對齊每一欄
formatted_row = ' | '.join(cell.ljust(max_lengths[i]) for i, cell in enumerate(row))
txt_file.write(formatted_row + '\n')
# 輸入檔案名稱
input_file = 'input.csv'
output_file = 'output.txt'
# 呼叫函式進行轉換
convert_csv_to_txt(input_file, output_file)
import pandas as pd
# 读取CSV文件
df = pd.read_csv('yourfile.csv', encoding='latin-1')
# 将所有单元格内容转换为文本格式
df = df.astype(str)
# 计算每一列中的单元格内最长内容的长度(中文字符和中文标点记为2个字符长度,其他英文字符记为1个字符长度)
lengths = []
for col in df.columns:
max_length = 0
for index, row in df.iterrows():
cell = row[col]
length = sum(2 if ord(c) >= 0x4e00 and ord(c) <= 0x9fff else 1 for c in cell)
if length > max_length:
max_length = length
lengths.append(max_length)
# 按照第二步的数据,将每个单元格的内容右对齐
formatted_df = df.copy()
for i, col in enumerate(formatted_df.columns):
formatted_df[col] = formatted_df[col].apply(lambda x: x.rjust(lengths[i]))
# 将格式化后的数据写入out.txt文件
formatted_df.to_csv('out.txt', index=False, header=True)