我目前正在为我自己的网站编写一个脚本,该网站托管游戏和其中很多游戏 游戏太多了,我必须编写一个脚本来自动为每个游戏创建一个文件 现在我陷入困境的是,我从文件夹的名称中获取游戏的名称,但替换目录的开头不起作用谈论 C:\Users\user\Desktop\Newfolder\
这是我的代码,它没有最好的格式,因为我认为其他人不需要看到它
for f,s in size_of_file: # file and size
if round(s/(1*1),3) > 10000000: # the hosting I'm using doesn't allow files above 10mb
print("Found Big File. Size: {} Path: {}".format(round(s/(1*1),3),os.path.join(path, f)))
gamename = path.replace(r'C:\Users\Logan\Desktop\Newfolder\'', r'')
f = open("{}.html".format(gamename),"w",encoding="utf-8") # create html file for the game this for some reason DOES work and the game name is correct
f.write(bigfile.replace("PLEASEREPLACEMEWITHTHEGAMETHATYOUARETRYINGTOREPLACEMEWITHAWUFIAWUIFIGUWAFGIUAW",gamename)) #unique text so that I can replace it
# for some reason here gamename is defined as C:\Users\Logan\Desktop\Newfolder\btd5 in comparison to where when I created the file it is only btd5
f.close()
else:
print("Found Small File. Size: {} Path: {}".format(round(s/(1*1),3),os.path.join(path, f)))
我尝试不使用变量而只使用
path.replace(r'C:\Users\Logan\Desktop\Newfolder\'', r'')
但这不起作用,我得到了相同的结果
您似乎正在尝试从目录路径中提取游戏名称并将其用于创建 HTML 文件。您遇到的问题可能与您使用
path.replace()
函数的方式有关。您需要确保正确地从目录路径中提取游戏名称并清理它。
import os
directory_path = r'C:\Users\Logan\Desktop\Newfolder'
for f, s in size_of_file: # file and size
if round(s / (1 * 1), 3) > 10000000: # File size check
print("Found Big File. Size: {} Path: {}".format(round(s / (1 * 1), 3), os.path.join(path, f)))
# Extract game name from the directory path
relative_path = os.path.relpath(path, directory_path) # Get relative path
game_name = os.path.basename(relative_path) # Get the game name
html_filename = "{}.html".format(game_name)
html_content = bigfile.replace("PLEASEREPLACEMEWITHTHEGAMETHATYOUARETRYINGTOREPLACEMEWITHAWUFIAWUIFIGUWAFGIUAW", game_name)
with open(html_filename, "w", encoding="utf-8") as f:
f.write(html_content)
else:
print("Found Small File. Size: {} Path: {}".format(round(s / (1 * 1), 3), os.path.join(path, f)))