I am trying to create a program that takes an input from a user for a file name and then a text string and removes the string from the file. I have been at this one for a while and I have exausted just about every idea I had to get this program to work.

def main():
    infile = open(input("Enter a file name: "), "r")
    outfile = ""
    str_rmv = input("Enter the string to be removed: ")
    for line in infile:
        print(line.replace(str_rmv, ""))

    for line in infile:
        outfile.write(line.replace(searchString, ""))

    lines = [line.replace(searchString, "") for line in outfile]
    outfile.seek(0)
    outfile.truncate()
    outfile.writelines(lines)

    with open(pathname, "r") as infile:
        with tempfile.NamedTemporaryFile("w") as outfile:
            for line in infile:
                outfile.write(line.replace(searchString, ""))
    shutil.move(outfile.name, pathname)
    infile.close()
    outfile.close()

    print("Done")

main()

Recommended Answers

All 2 Replies

This is what I have now, the problem is that the program creates an empty file when it should create a file that has what the old file did minus the string that the user wanted to remove. What can I do to fix this?

def main():
    inpath = input("Enter an input file: ")
    line = input("Enter what you want to remove: ")
    outpath = input("Enter an output file: ")
    with open(inpath, "r") as infile, open(outpath, "w") as outfile:
        for line in infile:
            outfile.write(line.replace(line, "") + "\n")
    print("Done.")

main()

the problem is that the program creates an empty file

Not sure what to do next

Test your program (note that the file is not technically "empty")

def main():
    inpath = input("Enter an input file: ")
    line = input("Enter what you want to remove: ")
    outpath = input("Enter an output file: ")
    with open(inpath, "r") as infile, open(outpath, "w") as outfile:
        for line in infile:
            print("replacing", line, "with", line.replace(line, ""))
            outfile.write(line.replace(line, "") + "\n")
    print("Done.")

main()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.