Reputation: 61
I'm completely new to python and I'm trying to rename a set of files using a string on a specific line within the file and use it to rename the file. Such string is found at the same line in each file.
As an example:
I'm trying to use this code, but I fail to figure out how to get it working:
for filename in os.listdir(path):
if filename.startswith("out"):
with open(filename) as openfile:
fourteenline = linecache.getline(path, 14)
os.rename(filename, fourteenline.strip())
Upvotes: 0
Views: 2235
Reputation: 1984
Take care providing the full path to the file, in case your not allready working in this folder (use os.path.join()
). Furthermore, when using linecache, you dont need to open
the file.
import os, linecache
for filename in os.listdir(path):
if not filename.startswith("out"): continue # less deep
file_path = os.path.join(path, filename) # folderpath + filename
fourteenline = linecache.getline(file_path, 14) # maybe 13 for 0-based index?
new_file_name = fourteenline[40:40+50].rstrip() # staring at 40 with length of 50
os.rename(file_path, os.path.join(path, new_file_name))
useful ressources:
Upvotes: 1