1

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.

2 Answers2

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

nosklo
  • 217,122
  • 57
  • 293
  • 297
  • 1
    Thank you it kinda works. The problem with loss of file extension remains. A new problem now is with illegal characters in the filename(mostly " and :) any easy way to strip them out? – user2766567 Sep 11 '13 at 08:55
0

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)
wflynny
  • 18,065
  • 5
  • 46
  • 67