Python作为一种强大的编程语言,其丰富的库和模块使得处理文件转换变得简单而高效。无论是转换文本格式、图像格式,还是处理其他类型的文件,Python都能提供多种方法来实现。以下是一些常见的文件转换方...
Python作为一种强大的编程语言,其丰富的库和模块使得处理文件转换变得简单而高效。无论是转换文本格式、图像格式,还是处理其他类型的文件,Python都能提供多种方法来实现。以下是一些常见的文件转换方法,以及如何使用Python3来轻松实现它们。
将文本文件转换为CSV格式通常涉及解析文本文件的每一行,并按照CSV的逗号分隔值格式进行重组。
import csv
def text_to_csv(text_file, csv_file): with open(text_file, 'r') as f: reader = csv.reader(f) with open(csv_file, 'w', newline='') as out_file: writer = csv.writer(out_file) for row in reader: writer.writerow(row)
# 使用示例
text_to_csv('input.txt', 'output.csv')将CSV文件转换为JSON格式通常需要解析CSV文件并将其转换为Python字典,然后将其序列化为JSON字符串。
import csv
import json
def csv_to_json(csv_file, json_file): with open(csv_file, 'r') as f: reader = csv.DictReader(f) data = list(reader) with open(json_file, 'w') as out_file: json.dump(data, out_file, indent=4)
# 使用示例
csv_to_json('input.csv', 'output.json')Python的Pillow库是一个强大的图像处理库,可以用来转换图像格式。
from PIL import Image
def convert_image_format(input_image, output_image, format): img = Image.open(input_image) img.save(output_image, format)
# 使用示例
convert_image_format('input.jpg', 'output.png', 'PNG')def resize_image(input_image, output_image, width, height): img = Image.open(input_image) img = img.resize((width, height)) img.save(output_image)
# 使用示例
resize_image('input.jpg', 'output_small.jpg', 500, 500)from pdf2image import convert_from_path
def pdf_to_images(pdf_file, output_folder): images = convert_from_path(pdf_file) for i, image in enumerate(images): image.save(f"{output_folder}/page_{i+1}.png")
# 使用示例
pdf_to_images('input.pdf', 'output_images')from docx import Document
def docx_to_pdf(docx_file, pdf_file): doc = Document(docx_file) doc.save(pdf_file)
# 使用示例
docx_to_pdf('input.docx', 'output.pdf')通过上述方法,你可以使用Python3轻松实现各种文件格式的转换。这些示例只是冰山一角,Python的库和模块可以让你实现更多复杂的文件处理任务。