[英]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.