如何从检查同名文件开始的文件中知道文件循环器是否已完成?

问题描述 投票:0回答:1

每个Meta可以有1-5个文件的基名,例如:.NET Framework 2.0。1) handling2) vehicles3) carvariations4) carcols5) dlctext我在循环中检查这些基名是否在元文件中,如果是,我就把它添加到一个可变的

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

我需要一种方法来检查特定的文件是否有一些arttibutes--就像在代码中指定的那样--我想把数据分别写到__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',
}

我应该怎么做才能使它像这样?

python python-3.x file-handling helper filehandle
1个回答
0
投票

解释

你发布的代码存在很多问题。

  1. 这个... open('__resource.lua', 'x') 乍起 FileExistsError 如果文件已经存在--但这完全不需要,因为用 "w" 模式下,如果它们不存在,就会自动被创建。
  2. 您将当前的工作目录改为 Paunch2 + '\\' + FolderCreatorName 两次,这是不必要的
  3. 第一个 "file {\n\n" 是加在 "resource_manifest_version" 因为你没有在写的最后加上换行符(对于 "resource_manifest_version")
  4. 你在每一个字后面加了两个新行字符 "file {"这不是你想做的事情--它会增加两行新的内容,而不是一行。
  5. 你在第二个for-loop里面的代码不是很好 DRY(不要重复自己) - 这本身并不是问题,但这是非常糟糕的做法,一般来说
  6. 每次你把文件名写到 __resource.lua缩进,您没有使用缩进(您没有使用 "\t" 字号)
  7. 在第二个for-loop之后,你要添加一个 "}\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 { }'s.

解决办法

为了做到这一点,我们首先需要将所有的文件名按名称分开,只有当我们看完所有的文件后,我们才能开始向 __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")
© www.soinside.com 2019 - 2024. All rights reserved.