将其代码放到服务器上,批量的路径格式需要进行转换,对应就需要一个脚本
实战中演示Window格式转换为Linux(批量进行局部转换)
适用单个文件的路径格式
1 2 3 4 5 6 7 8 |
# 示例路径 linux_path = "/home/user/documents/project"
# 将Linux路径中的斜杠转换为Windows路径格式 windows_path = linux_path.replace("/", "\\")
# 打印结果 print(windows_path) # 输出: \home\user\documents\project |
截图如下:
整体的路径转换成想要的
1 2 3 4 5 6 7 8 |
# 示例路径 linux_path = "/home/user/documents/project"
# 将Linux路径转换为Windows路径 windows_path = linux_path.replace("/home/user/documents", "C:\\Users\\user\\Documents")
# 打印结果 print(windows_path) # 输出: C:\Users\user\Documents\project |
截图如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def replace_paths_in_file(input_file, output_file, old_path, new_path): # 读取输入文件内容 with open(input_file, 'r') as file: file_content = file.read()
# 转换路径 updated_content = file_content.replace(old_path, new_path)
# 写入到输出文件 with open(output_file, 'w') as file: file.write(updated_content)
# 示例文件路径 input_file = 'input.txt' output_file = 'output.txt'
# 示例路径 old_linux_path = "/home/user/documents" new_windows_path = "C:\\Users\\user\\Documents"
# 调用函数进行转换 replace_paths_in_file(input_file, output_file, old_linux_path, new_windows_path) |
如果是未知的路径,则对应需要使用正则表达式进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import re
def replace_paths_in_file(input_file, output_file): # 定义正则表达式来匹配Linux路径 linux_path_pattern = re.compile(r'(/[^/ ]*)+')
def linux_to_windows_path(linux_path): # 将Linux路径中的斜杠转换为Windows路径格式 windows_path = linux_path.replace("/", "\\") # 例如,如果需要将某个特定的根路径转换为Windows的根路径 windows_path = windows_path.replace("\\home\\user\\documents", "C:\\Users\\user\\Documents") return windows_path
# 读取输入文件内容 with open(input_file, 'r') as file: file_content = file.read()
# 使用正则表达式转换所有匹配的路径 updated_content = linux_path_pattern.sub(lambda match: linux_to_windows_path(match.group(0)), file_content)
# 写入到输出文件 with open(output_file, 'w') as file: file.write(updated_content)
# 示例文件路径 input_file = 'input.txt' output_file = 'output.txt'
# 调用函数进行转换 replace_paths_in_file(input_file, output_file) |
原本在Window上跑的Yolov5,对应的路径不是Linux,如果要放到Linux上跑,需要转换为Linux的路径
但是他的标签路径起码几千条(VOC的数据集标签)
对应的代码如下:(只需批量的转换局部即可)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def convert_path(windows_path): # 转换基路径 linux_path = windows_path.replace('F:\\AI\\datasets\\VOC2007', '/home/l228/huoyanhao/yolov5/datasets/VOC/images')
# 将路径分隔符从反斜杠和混合斜杠转换为统一的斜杠 linux_path = linux_path.replace('\\', '/')
return linux_path
def batch_convert_paths(input_file, output_file): with open(input_file, 'r') as infile, open(output_file, 'w') as outfile: for line in infile: windows_path = line.strip() linux_path = convert_path(windows_path) outfile.write(linux_path + '\n')
# 输入文件和输出文件路径 input_file = 'windows_paths.txt' output_file = 'linux_paths.txt'
batch_convert_paths(input_file, output_file) |
将其转换成吱声想要的路径,截图如下: