Python Writing Output To Separate Files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lqnt1981
    New Member
    • Jun 2008
    • 1

    Python Writing Output To Separate Files

    Following is the code in python that opens all files under a directories and puts a comma in place of whitespace, I can see the output on the command line, but I am not sure what to do in order to write the output of each file read in the directory into a separate file.
    # whitespace by comma in every line

    import fileinput, string, sys, os
    from os.path import join


    if len(sys.argv) != 2:
    print "Enter: python %s input_directory " % os.path.basenam e(sys.argv[0])
    sys.exit(0)

    #Getting input from the command line
    directory= sys.argv[1]

    for root, dirs, files in os.walk(directo ry):
    for name in files:
    filename= os.path.join(ro ot,name)
    file= open(filename, 'r')

    #putting comma wherever there is occurence of whitespace in line
    for line in file:
    x= line.split()
    str = ''
    for i in x:
    str+=(","+i)
    str1= str.lstrip(',')

    print( str1)
    file.close()

    Please make the changes to the above code so that if there r 3 files under the given directory it weill create 3 separate output files with the result stored in them.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Please use code tags when posting code. The following will open a file, read each line, split each line into a list, rejoin the list with commas, then write the list to disk.
    [code=Python]filename = 'input_file.txt '
    outname = 'output_file.tx t'

    f = open(filename)
    lineList = [','.join(items) for items in [line.split() for line in f]]
    f.close()

    f = open(outname, 'w')
    f.write('\n'.jo in(lineList))
    f.close()[/code]

    Comment

    Working...