简体   繁体   中英

Python script to rename a file to the folder name

I am making a python script to change the name of a file in a folder to the same name of the folder. For example if a folder is called TestFolder and the txt file in the folder is called test, the script will make the file called TestFolder.txt.

But, how can make the script work outside of the directory it is located in? Beneath is my code so far, i hope i explained it good enough.

import os

temp = os.path.dirname(os.path.realpath(__file__))
src = "{temp}\\".format(temp=temp)

def renamer():
    path = os.path.dirname(src)
    folder = os.path.basename(path)
    os.rename("{directory}\\{file}".format(directory=src, file=listDir()),
              "{directory}\\{file}.txt".format(directory=src, file=folder))


def listDir():
    for file in os.listdir(src):
        if file.endswith(".txt"):
            return file


def main():
    print("Hello World")

    print(listDir())
    renamer()
    print(listDir())


if __name__ == "__main__":
    main()

Your problem is that you went to some trouble to specify the script location as the renaming path:

temp = os.path.dirname(os.path.realpath(__file__))
src = "{temp}\\".format(temp=temp)

def renamer():
    path = os.path.dirname(src)
    folder = os.path.basename(path)

The solution is simple: if you don't want the script's location as the path/folder, then don't do that. Put what you want in its place. Use the cwd (current working directory) to rename in the execution location; otherwise, re-code your program to accept a folder name as input. Either of these is readily available through many examples on line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM