How to rename a file using Python

后端 未结 12 1432
借酒劲吻你
借酒劲吻你 2020-11-22 13:47

I want to change a.txt to b.kml.

相关标签:
12条回答
  • 2020-11-22 14:38
    import os
    
    # Set the path
    path = 'a\\b\\c'  
    # save current working directory
    saved_cwd = os.getcwd()
    # change your cwd to the directory which contains files
    os.chdir(path)
    os.rename('a.txt', 'b.klm')
    # moving back to the directory you were in 
    os.chdir(saved_cwd)
    
    0 讨论(0)
  • 2020-11-22 14:39

    You can use os.system to invoke terminal to accomplish the task:

    os.system('mv oldfile newfile')
    
    0 讨论(0)
  • 2020-11-22 14:42

    os.rename(old, new)

    This is found in the Python docs: http://docs.python.org/library/os.html

    0 讨论(0)
  • 2020-11-22 14:43
    import shutil
    import os
    
    files = os.listdir("./pics/") 
    
    for key in range(0, len(files)):
       print files[key]
       shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")
    

    This should do it. python 3+

    0 讨论(0)
  • 2020-11-22 14:45

    Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.

    os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')
    
    0 讨论(0)
  • 2020-11-22 14:48

    Using the Pathlib library's Path.rename instead of os.rename:

    import pathlib
    
    original_path = pathlib.Path('a.txt')
    new_path = original_path.rename('b.kml')
    
    0 讨论(0)
提交回复
热议问题