目录
- 前言
- 1. 局部转换
- 2. 批量转换
- 3. 实战Demo
前言
将其代码放到服务器上,批量的路径格式需要进行转换,对应就需要一个脚本
实战中演示Window格式转换为linux(批量进行局部转换)
1. 局部转换
适用单个文件的路径格式
# 示例路径 linux_path = "/home/user/documents/project" # 将Linux路径中的斜杠转换为Windows路径格式 windows_path = linux_path.replace("/", "\\") # 打印结果 print(windows_path) # 输出: \home\user\documents\project
截图如下:
整体的路径转换成想要的
# 示例路径 linux_path = "/home/user/documents/project" # 将Linux路径转换为Windows路径 windows_path = linux_path.replace("/home/use编程r/documents", "C:\\Users\\user\\Documents") # 打印结果 print(windows_path) # 输出: C:\Uphpsers\user\Documents\project
截图如下:
2. 批量转换
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_cont编程ent.replace(old_path, new_path) # 写入到输出文件 with open(output_file, 'w') as file: file.write(updated_content) # 示例文件php路径 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)
如果是未知的路径,则对应需要使用正则表达式进行处理
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)
3. 实战Demo
原本在Window上跑的Yolov5,对应的路径不是Linux,如果要放到Linux上跑,需要转换为Linux的路径
但是他的标签路径起码几千条(VOC的数据集标签)对应的代码如下:(只需批量的转换局部即可)
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(outpuwww.devze.comt_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)
将其转换成吱声想要的路径,截图如下:
到此这篇关于python实现Window路径格式转换为Linux路径格式的代码的文章就介绍到这了,更多相关Python Window格式转Linux内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论