Skip to main content


Showing posts from August, 2014

Python: Change extension of all files in a folder

Dear Friends,

Below is the script that will change the extension of all the files from .exe to .txt. The script should be copied in the same folder, or change the path accordingly.

import os, sys

for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
  base_file, ext = os.path.splitext(filename)
  if ext == ".exe":
    os.rename(filename, base_file + ".txt")

Python: Cut a large text file in small files containing user specified lines in each file

Dear Friends,

Very often you need to cut a large file in small files which contains equal number of lines. Consider the following scenerio:

I have a text files which contains 1000000 lines. I want to split it in files that contains 15000 lines each. E.g, first file contains 1 to 15000 lines, next file 15001 to 30000 lines and so on.

The following script will not only do so, but it will also create files with meaningful names.

lines = open('myfile.txt').readlines()for i in range(0,1000000,15000): open('{0}_{1}.txt'.format(i+1, i+15000),'w').writelines(lines[i:i+15000])----------------------------------------------------------------------Notes:1. This will create files with names line 1_15000.txt which contain lines 1 to 15000,15001_30000.txt which contain lines 15001 to 30000 and so on.