0

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:

  • 10 files in the same path
  • the string is found in line number 14 and it starts at character number 40 and it is 50 characters in length
  • Then use the extracted string to rename the respective file

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())
Skandix
  • 1,916
  • 6
  • 27
  • 36
Moh
  • 61
  • 6
  • in case you need a start: `lines = open('myfile.txt').read().splitlines()` `new_file_name = lines[13][40:40+50]` `import os` `os.rename('myfile.txt', 'new_file_name.txt')`. probably this needs some finetuning and spellchecking .... – Skandix Sep 06 '18 at 09:01

1 Answers1

1

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:

Skandix
  • 1,916
  • 6
  • 27
  • 36
  • Thank you for the code. I tested the code it went smooth till the last line where the below error came across: os.rename(file_path, os.path.join(path, new_file_name)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:/path/to/the/file/out0.dat' -> 'C:/path/to/the/file/new_name\n' – Moh Sep 06 '18 at 09:59
  • I think it is related to the path length in windows, but I really don't know how to fix it – Moh Sep 06 '18 at 11:57
  • no, it's the `\n` (newline). Adding `.rstrip()` to the new filename should help to remove trailing spaces and newlines. (see edited answer) – Skandix Sep 06 '18 at 13:06