Find and replace within a text file using Python

后端 未结 3 1761

I have a text file which is about 400,000 lines long. I need to import this text file into a program which only accepts text files which are delimited with spaces or tabs, b

相关标签:
3条回答
  • 2020-12-02 19:36

    How about this:

    sed -i 's/;/ /g' yourBigFile.txt
    

    This is not a Python solution. You have to start this in a shell. But if you use Notepad, I guess you are on Windows. So here a Python solution:

    f1 = open('yourBigFile.txt', 'r')
    f2 = open('yourBigFile.txt.tmp', 'w')
    for line in f1:
        f2.write(line.replace(';', ' '))
    f1.close()
    f2.close()
    
    0 讨论(0)
  • 2020-12-02 19:47

    Python 3.2 has added ability to use this as context manager, so that the files that fail during processing for some reason will always get closed:

    import fileinput
    def main():
        with fileinput.input(inplace=True) as f:
            for line in f:
                line = line.replace(";", " ")
                print(line, end='')
    

    (inspiration)

    Use it by supplying it with the text file you want to process.

    0 讨论(0)
  • 2020-12-02 19:57

    with Python, you can use fileinput.

    import fileinput
    for line in fileinput.FileInput("file",inplace=1):
        line = line.replace(";"," ")
        print line,
    

    this will replace all your ";" to spaces in place.

    0 讨论(0)
提交回复
热议问题