简体   繁体   English

Python:如何将 N 行从一个文件移动到另一个文件

[英]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我正在尝试这样的事情,但是在 Python 而不是 PowerShell: https://askubuntu.com/questions/1105376/to-to--nother--file-how

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.我需要将前 100 行从文本文件移动(剪切,而不仅仅是复制)到另一个空/新文本文件。

Thanks in advance提前致谢

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM