问题
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