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

时间:2015-09-15 01:10:42

标签: python file file-io rename

我的文件夹中包含以下格式的文件:

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'

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

告诉你哪里出错了。

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

  

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

     

名为filename 的文件中获取line lineno。此功能永远不会引发异常 - 它将返回&#39;&#39;错误(终止换行符将包含在找到的行中。)

所以你不应该打开文件然后传入文件对象,而应该直接使用文件名。示例 -

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

答案 2 :(得分:0)

尝试使用更简单的方法

Date