Example code - Input Output

From 22101
Jump to navigation Jump to search

Replacing tabs with spaces

As you may have discovered by now, Python is very sensitive about mixing tabs and spaces in the indentation. This program discovers all the tabs and makes them into spaces. You can decide how many spaces a tab should be.
The program is meant to work in a Unix environment, and Jupyter Notebook will tend to make it superfluous.

filename = input("Filename: ")
spaceno = int(input("Number of spaces instead of a tab: "))

# Make a string with the correct amount of spaces
spacestring = ""
for i in range(spaceno):
    spacestring += " "

# open infile in current directory for reading
infile = open(filename, "r")

# read line by line, until the end of file
content = ""
for line in infile:
    # iterate over characters in the string 'line'
    for char in line:
        # if it's not a tab character, just keep it unchanged
        if char != "\t":
            content += char
        else:
            # replace with spacestring
            content += spacestring
infile.close()

# open output file for writing
outfile = open(filename, "w")
outfile.write(content)
outfile.close()