繁体   English   中英

使用python重命名目录中的所有文件以在每个文件中存在的行

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

我有一个充满以下格式文件的文件夹:

temp0.txt

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

这些文件中的每个文件的第二行都包含我要分别将其重命名为的字符串。 为了清楚起见,如果“ temp0.txt”在第二行中包含“ textfile0”,我希望将“ temp0.txt”重命名为“ textfile0.txt”。 同样,如果“ temp999.txt”在第二行中包含“ textfile123”,我希望将“ temp999.txt”重命名为“ textfile123.txt”。

以下是我到目前为止所拥有的,但是没有用。

import os, linecache

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

任何帮助将不胜感激!

我收到的错误如下:

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来获取必要的行。

只是告诉您您要去哪里。

linecache需要文件名作为第一个参数(作为字符串),而不是完整的文件。 文档-

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

名为filename的文件获取lineno。 此函数永远不会引发异常-它将在错误时返回''(找到的行将包含终止的换行符)。

因此,您不应该打开文件然后传递文件对象,而应直接使用filename。 范例-

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

尝试使用更简单的方法

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)

暂无
暂无

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

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