Rename .txt files to first line in file?

旧城冷巷雨未停 提交于 2019-12-11 15:36:28

问题


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.

Any help would be greatly appreciated, thank you.


回答1:


you need to open the file to get the first line from it. for line in filename is a for-loop that iterates over the filename, not the contents of the file, since you didn't open the actual file.

Also a for-loop is intended to iterate over all of the file, and you only want the first line.

Finally, a line from a text file includes the end-of-line character ('\n') so you need to .strip() that out.

import os
for filename in os.listdir("."):
   if filename.startswith("read"):
      with open(filename) as openfile:
        firstline = openfile.readline()
      os.rename(filename, firstline.strip())

hope that helps




回答2:


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)


来源:https://stackoverflow.com/questions/18729484/rename-txt-files-to-first-line-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!