让 os.rename 模块适用于自动化脚本时遇到问题
我循环遍历一个包含多个日志文件的文件,这些日志文件已分配了随机文件名。该脚本应该在日志中搜索包含“主机名”的行,然后提取分配的主机名以用作重新分配的文件名,这就是我遇到麻烦的地方......完全菜鸟......
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第二行中使用
file
作为变量名会替换第一行中的相同变量。您可能想对这两个变量使用不同的名称。您可能需要将
path
添加到这两个文件名的前面。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.You probably need to add
path
to the front of both of these filenames.