需要帮助将小python脚本从windows转换为linux

时间:2021-05-25 02:06:05

I'm no programmer but would like to use a Windows python script in Linux. It has trouble with the filenames I think. Probably because the \'s need to be /'s but there are a lot of them in this script and I don't know what they do. Hoping someone won't mind taking a look at it and maybe someone else can find it useful. It takes a csv file and uses it to create correct filenames for use with media servers. For example, I have a bunch of tv shows of a series in a folder and this will match up the files with the correct names in the csv file and rename the files.

我不是程序员,但想在Linux中使用Windows python脚本。我认为它的文件名有问题。可能是因为它需要成为/但是在这个剧本中有很多它们我不知道它们做了什么。希望有人不介意看看它,也许别人可以发现它有用。它需要一个csv文件并使用它来创建正确的文件名以供媒体服务器使用。例如,我在一个文件夹中有一系列电视节目,这将匹配csv文件中正确名称的文件并重命名文件。

Here it is:

这里是:

# Episode Name - File Renamer
# Renames files without accurate episode order using the Episode Name only
# Coded by: Tim.

# Import modules
import os
import glob
import csv

# Assign inital values
repeat = "true"
edit = "true"

#Define custom functions
def invalid_char(s):
    """
    Strip the invalid filename characters from the string selected.
    Feel free to add/remove additional .replace(X,X) as needed if you
    want to remove other characters even if they are valid.
    For example: , or [ or !
"""
return s.replace("?","").replace(":","").replace("*","").replace("<","").replace(">","").replace("|","").replace("/","").replace("\\","").replace('"',"")

def season(l):
"""
Takes the first cell of the CSV copied from the TVDB website
and strips out only the season.
"""
if l == "Special":
    season = "00"
else:
    season = l.split(" ")[0].zfill(2)
return season

def episode(l):
"""
Takes the first cell of the CSV copied from the TVDB website
and strips out only the episode. Pads a 0 before single digits.
"""
if l == "Special":
    episode = "00"
else:
    episode = l.split(" ")[-1].zfill(2)
return episode

# Overall loop, allows user to re-run the entire script
while repeat == "true":

# Checks if the user defined variables need to be edited
if edit == "true":

    # Prompt user to define static variables
    series_name = raw_input("Please enter your series name: ")
    #series_name = "Charlie Brown"
    print "\n"
    data = raw_input("Path to CSV: ")
    #data = "C:\lt\cb.csv"
    print "\n"
    dir1 = raw_input("Path to episodes (format C:\*): ")
    #dir1 = "M:\TV Shows\CB\all\*"
    print "\n"
    move = raw_input("Would you like to move renamed files? (Yes/No): ").lower()
    if move in ("y", "ye", "yes"):
        print "\n"
        print "Enter path to root folder where files should be moved"
        move_path = raw_input("and season folders will be created (format C:\Show\): ")
    edit = "false"
file_list = glob.glob(dir1)
print ("\n\n")

# Loop through file_list and look for matches in the CSV to the filename after the     prefix assigned
for file in file_list:
    fname = file
    ext = fname[-4:]
    with open(data, 'r') as file:
        reader = csv.reader(file)
        season_episode_name = ["S" + season(line[0]) + "E" + episode(line[0]) + " " + invalid_char(line[1]) for line in reader if invalid_char(line[1].lower()) in fname.lower() and line[1].lower() != ""]
        season_dir = (''.join(season_episode_name)).split("E")[0][1:]
    if season_episode_name:
        season_episode_name = ''.join(season_episode_name)
        fname2 = dir1[:-1] + series_name + " " + season_episode_name + ext

        # If user chose to move files to another directory, then fname2 has the path replaced
        if move in ("y", "ye", "yes"):
            fname2 = move_path + "Season " + season_dir + "\\" + fname2[len(dir1[:-1]):]

            # Generates the season directory if does not already exist
            if not os.path.exists(move_path + "Season " + season_dir):
                os.makedirs(move_path + "Season " + season_dir)

        # Rename file and move if user requested
        print fname + "\n    >>> " + fname2 + "\n"
        os.rename(fname, fname2)

    else:
        print fname + "\n    >>> " "Unable to locate match, please rename manually.\n"

# Check if user wants to repeat, edit or exit
repeat = raw_input ("\n\nType R to run again, Type E to edit the parameters, or Q to quit: ")
if repeat.lower() in ("r", "retry"):
    repeat = "true"
    print "\nRunning again with the same parameters.."
elif repeat.lower() in ("e", "edit"):
    edit = "true"
    repeat = "true"
    print "\nEditing paramaters before running again.."
elif repeat.lower() in ("q", "quit"):
    repeat = "false"
    print "\nQuitting..."
else:
    repeat = "false"
    print "\nInvalid command."

# When repeat no longer is "true" the script exiits with the below message
else:
raw_input("\n\nPress enter to exit...")

1 个解决方案

#1


1  

to make window path work on Linux you can use os.path.join

要使窗口路径在Linux上运行,您可以使用os.path.join

Here is an example:

这是一个例子:

say you have a directory like this

说你有这样的目录

C:\Documents\Example\file.py

to acsess that without using the windows \ you can do:

无需使用Windows即可执行以下操作:您可以执行以下操作:

os.path.join('C:', 'Documents', 'Example','file.py')

and its the same thing but it will work for linux!

它同样的东西,但它适用于Linux!

#1


1  

to make window path work on Linux you can use os.path.join

要使窗口路径在Linux上运行,您可以使用os.path.join

Here is an example:

这是一个例子:

say you have a directory like this

说你有这样的目录

C:\Documents\Example\file.py

to acsess that without using the windows \ you can do:

无需使用Windows即可执行以下操作:您可以执行以下操作:

os.path.join('C:', 'Documents', 'Example','file.py')

and its the same thing but it will work for linux!

它同样的东西,但它适用于Linux!