我怎么知道文件循环器是否检查完以相同名称开始的文件

2024-09-26 22:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

每个元可以有1-5个文件,基本名称如下: 1) handling2) vehicles3) carvariations4) carcols5) dlctext 我在一个循环中检查这些基名中是否有一个在元文件中——如果为true,我将其添加到变量中

IDEA FOR THE FILES THATS IN THE FOLDER

name-handling.meta
name2-handling.meta
name2-carvarations.meta
name3-handling.meta
name3-dlctext.meta
name3-vehicles.meta

我需要一种方法来检查特定文件是否有一些arttibute(如代码中指定的),并且我想将数据分别写入_resource.lua文件和每个文件。示例如下:

The Code :

    os.chdir(Paunch2 + '\\' + FolderCreatorName)

    ResourceData = open('__resource.lua', 'x')
    print('ResourceFile Were Openned')
    ResourceData = open('__resource.lua', 'w')
    ResourceData.write("resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'")

    os.chdir(Paunch2 + '\\' + FolderCreatorName)
    print('Entered the Folder :', Paunch2 + '\\' + FolderCreatorName, '\n\nLets Gooo We are inside the looping :D')

    for dirpath, dirnames, files in os.walk('.') :
        ResourceData.write("file {\n\n")
        for file in files :
            if file.endswith('.meta') and 'handling' in str(file):
                print('meta')
                HandlingFile = str(file)
                ResourceData.write(f"'{HandlingFile}',\n")
                print(f"data file 'HANDLING_FILE' '{HandlingFile}'")
            elif file.endswith('.meta') and 'vehicles' in str(file):
                VehiclesFile = str(file)
                ResourceData.write(f"'{VehiclesFile}',\n")
                print(f"data file 'VEHICLE_METADATA_FILE' '{VehiclesFile}'")
            elif file.endswith('.meta') and 'carvariations' in str(file):
                CarVariationsFile = str(file)
                ResourceData.write(f"'{CarVariationsFile}',\n")
                print(f"data file 'VEHICLE_VARIATION_FILE' '{CarVariationsFile}'")
            elif file.endswith('.meta') and 'carcols' in str(file):
                CarcolsFile = str(file)
                ResourceData.write(f"'{CarcolsFile}',\n")
                print(f"data file 'CARCOLS_FILE' '{CarcolsFile}'")
            elif file.endswith('.meta') and 'dlctext' in str(file):
                DLCTextFile = str(file)
                ResourceData.write(f"'{DLCTextFile}',\n")
                print('Dlctext is working')
            elif file.endswith('.meta') and 'vehiclelayouts' in str(file):
                LAYOUT = str(file)
                ResourceData.write(f"'{LAYOUT}',\n")
                print(f"data file 'VEHICLE_LAYOUTS_FILE' '{LAYOUT}'")

Output in the File that printing in :

resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'file {

'f777-carvariations.meta',
'f777-handling.meta',
'f777-vehicles.meta',
'superkart-carcols.meta',
'superkart-carvariations.meta',
'superkart-handling.meta',
'superkart-vehicles.meta',
'wmfenyr-carcols.meta',
'wmfenyr-carvariations.meta',
'wmfenyr-dlctext.meta',
'wmfenyr-handling.meta',
'wmfenyr-vehicles.meta',
file {

IT HAVE TO BE LIKE :

file {
   'f777-carvariations.meta',
   'f777-handling.meta',
   'f777-vehicles.meta',
}
file {
   'superkart-carcols.meta',
   'superkart-carvariations.meta',
   'superkart-handling.meta',
   'superkart-vehicles.meta',
}
file {
   'wmfenyr-carcols.meta',
   'wmfenyr-carvariations.meta',
   'wmfenyr-dlctext.meta',
   'wmfenyr-handling.meta',
   'wmfenyr-vehicles.meta',
}

我该怎么做才能让它变成这样


Tags: andinmetafilewriteprinthandlingstr
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:15

解释

您发布的代码存在许多问题:

  1. 如果文件已经存在,则开始时的open('__resource.lua', 'x')可能会引发FileExistsError,但根本不需要它,因为使用"w"模式打开的文件在不存在时会自动创建
  2. 将当前工作目录更改为Paunch2 + '\\' + FolderCreatorName两次,这是不必要的
  3. 第一个"file {\n\n"被添加到"resource_manifest_version"的顶部,因为您没有在写入的末尾添加换行符(对于"resource_manifest_version"
  4. 在每个"file {"之后添加两个换行符,这不是您想要做的事情-它将添加两个新行而不是一个新行
  5. 第二个for循环中的代码不是很DRY (Don't Repeat Yourself)——这本身不是问题,但通常是非常糟糕的做法
  6. 每次向__resource.lua写入文件名时,都没有对其进行缩进(没有使用"\t"字符)
  7. 在第二个for循环之后,您希望添加一个"}\n",这样就可以有一个右括号

以上所有操作将导致您的代码如下所示:

import os

os.chdir(Paunch2 + '\\' + FolderCreatorName)

ResourceData = open('__resource.lua', 'w')
ResourceData.write(
    "resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'\n\n"
)

for dirpath, dirnames, files in os.walk('.'):
    # Only one newline character is necessary, you don't need to newline twice
    ResourceData.write("file {\n")

    # You're code wasn't very DRY (Don't Repeat Yourself),
    # so now all it's doing is writing: "\t'{file}',".
    # The "\t" is needed for the indentation,
    # "'{file}'" writes the filename (automatically converts it to a string
    # so no need to call `str(file)`) and ",\n" at the end is to fit the
    # format you asked for.
    for file in files:
        ResourceData.write(f"\t'{file}',\n")
        print(f"Data file: '{file}'")

    # Writes a "}" at the end with a newline character.
    ResourceData.write("}\n")

现在,从我看来,这不是你想要的。您希望将文件名分隔为不同的file { }

解决方案

为了做到这一点,我们首先需要按名称分隔所有文件名,只有在我们查看了所有文件之后,我们才能开始写入__resource.lua(除非您确定您的文件系统对文件名进行了排序)。我们可以使用dict存储名称,因为键和值可以是文件名列表:

import os

os.chdir(Paunch2 + '\\' + FolderCreatorName)

ResourceData = open('__resource.lua', 'w')
ResourceData.write(
    "resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'\n\n"
)

files_dict = {}

for dirpath, dirnames, files in os.walk('.'):
    for file in files:
        # Gets the name of the file (e.g. name portion of 'name-handling.meta' -> 'name')
        name = file.split("-")[0]
        try:
            # If the key 'name' exists, it gets appended to the 'files_dict[name]'
            files_dict[name].append(file)
        except KeyError:
            # If the key 'name' doesn't exist,
            # it creates a list at 'files_dict[name]' and adds file to it
            files_dict[name] = [file]

        print(f"Data file: '{file}'")

# Writes everything to '__resource.lua' - similar to how the previous code sample works
for value in files_dict.values():
    ResourceData.write("file {\n")

    for file in value:
        ResourceData.write(f"\t{file},\n")

    ResourceData.write("}\n")

如果文件系统自动对文件名进行排序,我们只需检查当前文件名是否与上一个文件名相同-如果相同,则只需将文件添加到当前file { },否则关闭当前file { }并启动一个新文件:


import os

os.chdir(Paunch2 + '\\' + FolderCreatorName)

ResourceData = open('__resource.lua', 'w')
ResourceData.write(
    "resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'\n\n"
)

last_name = None

for file in os.listdir("."):
    if os.path.isfile(file):
        # Splits the name part of the filename (e.g. name-handling.meta -> name)
        name = file.split("-")[0]

        # If the name is not the same as the last one, start a new `file { }`
        if last_name != name:
            ResourceData.write("}\n")
            ResourceData.write("file {\n")

        # Add current file
        ResourceData.write(f"\t{file},\n")

        # Set 'last_name' to the current 'name'
        last_name = name

        print(f"Data file: '{file}'")

# Add a closing bracket at the end
ResourceData.write("}\n")

相关问题 更多 >

    热门问题