#This Python code removed newline character at the end of each line in a text #file and combines the statement in length of string is smaller than the size #specified by vairable nL. #------------------------------------------------------------------------------ import sys, os #------------------------------------------------------------------------------ #Check if user has specified text file on the command line. If not, Sample.txt #is defined as input file name. if (len(sys.argv) < 2): in_f = 'Sample.txt' else: in_f = str(sys.argv[1]) if (os.path.isfile(in_f) == False): print("\nExiting! Input file is: ", in_f, ' \n') print("Specified input text file does not exist in current directory.\n") sys.exit() out_f = 'TrimmedFile.txt' fi = open(in_f, mode="r", encoding="utf-8") txt = fi.readlines() nL = len(txt) nW = 80 i = 0 tt = '' with open(out_f, 'w') as fo: for i in range(nL): #Check for blank line (start of a new paragraph) if (txt[i] == '\n'): fo.write(tt) fo.write('\n') tt = '\n' #Continue adding lines till a newline found or size < mid chars else: tt = tt + txt[i].replace('\n', ' ') #Write line to the file if size exceeds nL and EOF is not reached if (len(tt) >= nW and i < nL): fo.write(tt) fo.write('\n') tt = '' #Write the concatenated line irrespective of size once EOF file reached elif (i == nL-1): fo.write(tt) fo.write('\n') i = i + 1 fi.close fo.close