我有以下完整的文件夹格式:
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'
试着用一种更简单的方法
尝试使用内置的
openfile.readline()
而不是linecache来获取所需的行。在只是想告诉你你哪里做错了。在
linecache
需要文件名作为第一个参数(字符串),而不是完整的文件对象。来自documentation -因此,您不应该打开文件然后传入file对象,而应该直接使用文件名。示例-
相关问题 更多 >
编程相关推荐