提供一个python code,遍历文件夹中所有文件,并将文内容保存为unix
时间: 2024-09-14 11:11:09 浏览: 40
你可以使用Python的os和path模块来遍历文件夹并转换文件内容为Unix格式。下面是一个基本示例,它假设所有的文件都是文本文件(`.txt`或其他支持编码的文件),并使用`chardet`库检测文件的编码,然后将其转换为UTF-8格式:
```python
import os
import chardet
def convert_to_unix_format(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if not file.endswith(('.txt', '.csv')): # 可以按需要修改这里以处理更多文件类型
continue
full_path = os.path.join(root, file)
with open(full_path, 'rb') as read_file:
byte_content = read_file.read()
detected_encoding = chardet.detect(byte_content)['encoding']
try:
content = byte_content.decode(detected_encoding).replace('\r\n', '\n') # Unix格式换行符
unix_content = content.encode('utf-8')
except UnicodeDecodeError:
print(f"Failed to decode {full_path}, skipping...")
with open(full_path, 'wb') as write_file:
write_file.write(unix_content)
# 调用函数并传入你要处理的文件夹路径
convert_to_unix_format('/path/to/your/directory')
```
阅读全文