A bit long but fun exercise nonetheless:
# Function to count the number of leading spaces in a string # Basically, this counts the number of consecutive elements that satisfy being spaces def count_leading_spaces(s): if not s: return 0 else: curr_char = s[0] if curr_char != ' ': return 0 else: idx = 1 curr_char = s[idx] while curr_char == ' ': idx += 1 try: curr_char = s[idx] except IndexError: return idx return idx
Finally, open the file and do some work:
with open('file.txt', 'r') as f: data = [] for i, line in enumerate(f): # Don't do anything to the field names if i == 0: new_line = line.rstrip() else: n_leading_spaces = count_leading_spaces(line) # Impute periods for spaces new_line = ('.'*n_leading_spaces + line.lstrip()).rstrip() data.append(new_line)
Results:
>>> print('\n'.join(data)) top f1 f2 f3 ...sub1 f1 f2 f3 ...sub2 f1 f2 f3 ......sub21 f1 f2 f3 ...sub3 f1 f2 f3
You can also make it so much easier:
with open('file.txt', 'r') as f: data = [] for i, line in enumerate(f): # Don't do anything to the field names if i == 0: new_line = line.rstrip() else: n_leading_spaces = len(line) - len(line.lstrip()) # Impute periods for spaces new_line = line.lstrip().rjust(len(line), '.').rstrip() data.append(new_line)
source share