使用python将目录中的所有文件重命名为每个文件中的行

2024-04-26 04:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下完整的文件夹格式:

temp0.txt

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

每一个文件的第二行都包含我想分别将每个文件重命名为的字符串。为了清楚起见,如果“temp0.txt”在第二行包含“textfile0”,我希望将“temp0.txt”重命名为“textfile0.txt”。类似地,如果“temp999.txt”第二行包含“textfile123”,我希望“temp999.txt”重命名为“textfile123.txt”。在

以下是我到目前为止所拥有的,但它不起作用。在

^{pr2}$

任何帮助将不胜感激!在

我收到的错误如下:

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'

Tags: 文件inpytxtusrlinefilenamefile
3条回答

试着用一种更简单的方法

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)

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

只是想告诉你你哪里做错了。在

linecache需要文件名作为第一个参数(字符串),而不是完整的文件对象。来自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).

因此,您不应该打开文件然后传入file对象,而应该直接使用文件名。示例-

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

相关问题 更多 >