在Python中,转换文件格式通常可以通过使用特定的库来实现。以下是一些常见的文件格式转换示例:
文档格式转换
将TXT转换为DOCX:
from spire.doc import Document
加载.txt文档
document = Document()
document.LoadFromFile('溯源码.txt')
将文档另存为docx格式
document.SaveToFile('Word转Txt.docx', FileFormat.Docx)
document.Close()
将DOCX转换为TXT:
from spire.doc import Document
加载.docx文档
document = Document()
document.LoadFromFile('溯源码.docx')
将文档另存为txt格式
document.SaveToFile('Word转Txt.txt', FileFormat.Txt)
document.Close()
图片格式转换
将JPG转换为PNG:
import cv2
读取JPG文件
img = cv2.imread('a.jpg')
保存为PNG文件
cv2.imwrite('a.png', img)
数据格式转换
将文本文件转换为CSV:
import csv
假设文本文件名为 'input.txt', 每行数据由逗号分隔
input_file = 'input.txt'
output_file = 'output.csv'
with open(input_file, 'r') as infile, open(output_file, 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(row)
将文本文件转换为JSON:
import json
读取文本文件内容
with open('input.txt', 'r') as file:
data = file.read()
将内容转换为Python列表
lines = data.split('\n')
data_list = [list(map(int, line.split(','))) for line in lines]
将列表转换为JSON格式并保存
with open('output.json', 'w') as file:
json.dump(data_list, file)
其他格式转换
将文本文件转换为Shapefile(SHP):
使用GeoPandas读取KML文件并转换为SHP格式
import geopandas as gpd
读取KML文件
gdf = gpd.read_file('input.kml')
保存为SHP格式
gdf.to_file('output.shp', driver='ESRI Shapefile')
这些示例展示了如何使用Python库进行文件格式转换。根据你的具体需求,你可能需要安装相应的库,例如`spire.doc`、`opencv`、`csv`、`json`和`geopandas`。使用`pip`安装这些库,例如:
pip install spire.doc opencv-python csv json geopandas