I hate having to format questions around here. Adding four spaces to each source file and the correct name at the top of each source file becomes a headache when I have to post longer questions.
This is a simple python question parser that takes in arguments from the console and prints out correct format for a CodeReview question. Any suggestions on how to make this code more readable, concise and pythonic would be appreciated.
Question Parser.py
import os
import sys
import argparse
def format_string(PATH,EXTENSION):
source_files=[f for f in os.listdir(PATH) if os.path.isfile(os.path.join(PATH,f))]
source_files=[f for f in source_files if f.endswith(EXTENSION)]
indentation=4
formatted_string=""
for source_file in source_files:
formatted_string+= ("**%s**\n\n" % source_file)
with open(os.path.join(PATH,source_file)) as source:
for line in source.readlines():
formatted_string+=(" "*indentation+"".join(line))
return formatted_string
if __name__=="__main__":
parser=argparse.ArgumentParser(description="Automatic formatter for CodeReview Stackexchange Questions")
parser.add_argument("-p","--path",help="Path for the source files. Default is the current directory",nargs="?",default=os.getcwd(),const=os.getcwd())
parser.add_argument("header",help="The file that is added to the top of the question")
parser.add_argument("-e","--extension",help="Filter by the type of source files that is present in the directory",nargs="+",default="")
parser.add_argument("-o","--out",help="Output the result to a file. By default outputs to the console.",nargs="?")
args=parser.parse_args()
if not os.path.isfile(args.header):
raise parser.error("Header file doesnot exist.\nPlease specify a correct header file path")
if os.path.exists(args.path):
question="".join(open(args.header).readlines())
question+="\n"+format_string(args.path,tuple(args.extension,))
if not (args.out==None):
with open(args.out,"w") as outfile:
outfile.write(question)
else:
print(question)
else:
raise parser.error("Path doesnot exist.")