简体   繁体   English

将.txt文件重命名为文件的第一行?

[英]Rename .txt files to first line in file?

I've got a lot of .txt files with names starting with "read" that I want to rename. 我有很多.txt文件,它们的名称以“ read”开头,我想对其重命名。 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. 任何帮助将不胜感激,谢谢。

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. for line in filename中的for line in filename是一个for循环,它遍历文件名而不是文件内容,因为您没有打开实际文件。

Also a for-loop is intended to iterate over all of the file, and you only want the first line. 另外,for循环旨在遍历所有文件,并且您只需要第一行。

Finally, a line from a text file includes the end-of-line character ( '\\n' ) so you need to .strip() that out. 最后,文本文件中的一行包含行尾字符( '\\n' ),因此您需要将.strip()删除。

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 希望能有所帮助

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM