文件读写

基本操作及问题

遍历指定文件夹下的文件:

1
2
3
4
5
6
# 遍历文件夹
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.csv'): # 检查文件扩展名是否为 .csv
csv_path = os.path.join(root, file) # 获取文件的完整路径
print(f"找到 CSV 文件: {csv_path}")

OpenCV读取中文路径失败

在 OpenCV 中,cv2.imread 函数在处理中文路径时存在问题,因为它底层使用的是不支持中文编码的函数。为了解决这个问题,可以考虑使用 numpycv2.imdecode 来读取图像。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 检查文件是否存在
if not os.path.exists(image_path):
print(f"文件不存在: {image_path}")
return 0

try:
# 以二进制模式读取图像文件
with open(image_path, 'rb') as f:
img_bytes = np.asarray(bytearray(f.read()), dtype=np.uint8)
# 使用 cv2.imdecode 解码图像
original_img = cv2.imdecode(img_bytes, cv2.IMREAD_COLOR)
if original_img is None:
print(f"无法读取图像: {image_path},可能文件损坏。")
return 0
else:
print("图像读取成功")
# 在这里添加后续处理逻辑
return original_img
except Exception as e:
print(f"读取图像时出现错误: {e}")
return 0

CSV表格读取

注意编码问题,未注明编码即为使用utf-8。如果编码未知,可以尝试使用记事本打开查看编码。

1
2
df = pd.read_csv(csv_file, encoding='gbk')
data = df['column'].values
作者

sonder

发布于

2025-01-23

更新于

2025-03-24

许可协议