我有一个文件name.txt
,想要用pyhton重命名它。
my_path = "/home/user/folder1/folder2/name.txt
new_name= "name2.txt"
os.rename(my_path, new_name)
当我执行此程序时,它可以工作,但是新文件与python程序位于同一个文件夹中。有没有办法通过变量将新文件放入my_path
目录而不是硬编码?
我尝试了new_name = my_path - "name.txt"
,但它无效
编辑通过以下答案让它发挥作用:
my_path = "/home/user/folder1/folder2/name.txt"
new_name ="name2.txt"
new_name = os.path.join(os.path.dirname(my_path), new_name)
os.rename(my_path, new_name)
答案 0 :(得分:1)
>>> os.path.join(os.path.dirname("/home/user/folder1/folder2/name.txt"), "name2.txt")
'/home/user/folder1/folder2/name2.txt'