简体   繁体   中英

Rename all files in directory to line present in each file using python

I have a folder full of files in the following format:

temp0.txt

temp1.txt
temp3.txt
.
..
temp999.txt
...

The second line of each of these files contains the string I want to rename each file to respectively. To be clear, if "temp0.txt" contains "textfile0" in the second line, I want "temp0.txt" to be renamed to "textfile0.txt". Similarly, if "temp999.txt" contains "textfile123" in the second line, I want "temp999.txt" to be renamed to "textfile123.txt".

The following is what I have so far, but it doesn't work.

import os, linecache

for filename in os.listdir("."):
  with open(filename) as openfile:
    firstline = linecache.getline(openfile, 2)
  os.rename(filename, firstline.strip()+".txt")

Any help would be greatly appreciated!

The error I receive is as follows:

Traceback (most recent call last):
  File "rename_ZINC.py", line 5, in <module>
    firstline = linecache.getline(openfile, 2)
  File "/usr/lib64/python2.7/linecache.py", line 14, in getline
    lines = getlines(filename, module_globals)
  File "/usr/lib64/python2.7/linecache.py", line 40, in getlines
    return updatecache(filename, module_globals)
  File "/usr/lib64/python2.7/linecache.py", line 75, in updatecache
    if not filename or (filename.startswith('<') and filename.endswith('>')):
AttributeError: 'file' object has no attribute 'startswith'

尝试使用内置的openfile.readline()而不是linecache来获取必要的行。

Just to tell you where you are going wrong.

linecache requires a filename as the first argument (as a string) , not the complete file obect. From documentation -

linecache.getline(filename, lineno[, module_globals])

Get line lineno from file named filename . This function will never raise an exception — it will return '' on errors (the terminating newline character will be included for lines that are found).

So you should not open the file and then pass in the file object, instead you should have directly used the filename . Example -

for filename in os.listdir("."):
  secondline = linecache.getline(filename , 2)
  os.rename(filename, secondline.strip()+".txt")

Try using a simpler method

import os,re

def changeName(filename):
    with open(filename, "r") as f:
        line = next(f)
        secondline = next(f)
        if secondline == "textfile" + str(re.search(r'\d+', filename).group()): 
            #re.search() gets the first integer in the filename
            os.rename(filename, secondline + ".txt")

for root, dirs, files in os.walk("Directory"):
    for file in files:
        file = os.path.join(root, file)
        changeName(file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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