将.txt文件重命名为文件的第一行? [英] Rename .txt files to first line in file?

查看:196
本文介绍了将.txt文件重命名为文件的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多.txt文件,它们的名称以"read"开头,我想对其重命名.我希望使用文件的第一行来命名它们.我是一个非常糟糕的程序员,但是我已经放手了,现在我被卡住了.

I've got a lot of .txt files with names starting with "read" that I want to rename. I want them to be named with the first line in the file. I'm a really lousy programmer, but I've given it a go and now I'm stuck.

import os
for filename in os.listdir("."):
   if filename.startswith("read"):
      for line in filename:
        os.rename(filename, line)

此脚本目前不执行任何操作,即使它可以正常工作,我也可以肯定文件不会保留其扩展名.

At the moment the script does nothing and even if it worked I'm pretty sure the files wouldn't keep their extensions.

非常感谢您的帮助.

推荐答案

如果将内部循环替换为类似内容,该怎么办?

What if you replaced your inner loop with something like:

if not filename.startswith("read"): continue
base, ext = os.path.splitext(filename)
with open(filename, 'r') as infile:
    newname = infile.next().rstrip()
newname += ext
os.rename(filename, newname)

这篇关于将.txt文件重命名为文件的第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆