让 os.rename 模块适用于自动化脚本时遇到问题

发布于 2025-01-16 02:28:29 字数 473 浏览 2 评论 0原文

我循环遍历一个包含多个日志文件的文件,这些日志文件已分配了随机文件名。该脚本应该在日志中搜索包含“主机名”的行,然后提取分配的主机名以用作重新分配的文件名,这就是我遇到麻烦的地方......完全菜鸟......

  import os

path = "/Users/Joel/Desktop/logs"

for file in os.listdir(path):
    with open(f"{path}/{file}") as log:
        for line in log:
            if "hostname" in line:
                desired_filename = line.split()[1].replace('"','')
                os.rename(f'{path}/{file}', f'{path}/{desired_filename}')
                

Im looping through a file with multiple log files that have been assigned a randomized filename. The script should search within the log for the line containing "hostname" and then pull out the assigned hostname to use as the re-assigned file name, which is where im having trouble...total noob....

  import os

path = "/Users/Joel/Desktop/logs"

for file in os.listdir(path):
    with open(f"{path}/{file}") as log:
        for line in log:
            if "hostname" in line:
                desired_filename = line.split()[1].replace('"','')
                os.rename(f'{path}/{file}', f'{path}/{desired_filename}')
                

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎盛开的樱花 2025-01-23 02:28:29
for file in os.listdir(path):
    with open(f"{path}/{file}") as file:

在第二行中使用 file 作为变量名会替换第一行中的相同变量。您可能想对这两个变量使用不同的名称。

        os.rename(file, desired_filename)

您可能需要将 path 添加到这两个文件名的前面。

for file in os.listdir(path):
    with open(f"{path}/{file}") as file:

Using file as a variable name in the second line replaces the same variable from the first line. You probably want to use different names for these two variables.

        os.rename(file, desired_filename)

You probably need to add path to the front of both of these filenames.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文