Search code examples
pythoncopycut

Python: How to move N lines from one file to another


I am trying something like this, but in Python and not PowerShell: https://askubuntu.com/questions/1105376/how-to-move-n-lines-from-one-file-to-another

Can somebody help me? I need to move (cut, not only copy) the first 100 lines from a text file to another empty/new text file.

Thanks in advance


Solution

  • x = 100
    with open("C:/path/to/file/you/want/to/copy/from",'r') as f1:
        data = f1.readlines()
    with open("C:/path/to/file/you/want/to/copy/from",'w') as f1:
        for line in data[x:]:
            f1.write(line)
    with open("C:/path/to/file/you/want/to/copy/to",'w') as f2:
        for line in data[:x]:
            f2.write(line)