1

I wrote a very basic program to remove quotation marks from a text file. I have about 50 files I need to run and would rather run the program for all text files in a directory...

The big issue I am having is that I need the files to be read one at a time, and once the " are stripped, all the contents of the file outputted to a new file which uses the name of the input file.

For example:

As I have it now, the program takes the input file name as an argument, and creates the output file name as the infile name + _output.txt. How do I make it so it processes all the text files in a directory but names the files how I want it to?

My program:

import sys

if len(sys.argv) <2:
    print "Usage: python %s requires input file" % (sys.argv[0])
    sys.exit()

infile = sys.argv[1]
outfile = infile.split(".")[0] + "_output.txt"

INFH = open(infile)
OFH = open(outfile, "w")

print "Output File = %s" % (outfile)

for line in INFH:
    line=line.strip('\n').replace('\"','')

    print >> OFH, line
INFH.close()
8
  • 1
    Strange indentation... Commented Apr 18, 2016 at 15:49
  • I'ts from trying to cooperate with stack overflow's code block system for asking questions Commented Apr 18, 2016 at 15:55
  • Use os.listdir(path) and os.path.isfile(path) for this. Commented Apr 18, 2016 at 15:58
  • I understand using os.listdir, but how does os.path.isfile help? Commented Apr 18, 2016 at 15:59
  • 1
    os.listdir(path) returns files and folders in a directory. Use os.path.isfile(path) to make shure it's a file. Commented Apr 18, 2016 at 16:02

1 Answer 1

2

You can do it like this:

import sys, os

if len(sys.argv) < 2 and not os.path.isdir(sys.argv[1]):
    print("Usage: python {} directory".format(sys.argv[0]))
    sys.exit()

for entry in os.listdir(sys.argv[1]):
    if os.path.isfile(entry):
        infile = entry
        outfile = infile.split(".")[0] + "_output.txt"

        INFH = open(infile)
        OFH = open(outfile, "a")

        print("Output File = {}".format(outfile))

        for line in INFH:
            line = line.strip('\n').replace('\"','')
            OFH.write(line)

        INFH.close()

Just add an directory instead of an file as argument.

Sign up to request clarification or add additional context in comments.

3 Comments

This returns an IndexError:list index out of range
Hmm, do you use sth. like python yourfile.py ./dir/?
@cobaltchaos I've made some changes to the code, please try again. Works for me under Windows 10 and Python 3.4.4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.