導航:首頁 > 編程語言 > Python刪除文件中第n行行

Python刪除文件中第n行行

發布時間:2023-04-20 06:29:12

1. python 刪除特定幾行

思路:

先讀入一個文件,自動保存為列表類型,每行為一個元素

然後刪除列表中索引為 0,1,2 的三個元素


以下代碼調試通過:

f = open("/Users/mfhj-dz-001-119/Downloads/text001.txt")
lines = f.readlines()
print(' original lines is:', lines)
del lines[0:2]
print(' now the lines is:', lines)


讀入的文件:

2. python如何刪除行

使用open()打開文件,fh = open("asdf.txt", "r"),fh.readlines()這樣就得到了一個所有行的序列,你可以輸出看一下,如果你不想要哪行,可以使用序列的方法刪除掉,list.pop()這樣。
http://proupy.com

3. python遍歷文本並刪除特定內容

按 指定行數 分頁讀取好處理:

defiterpage(istream,pagesize):
buffer=[]
fordatainistream:
buffer.append(data)
iflen(buffer)>=pagesize:
yieldbuffer
buffer=[]
ifbuffer:
yieldbuffer

withopen("source.txt",'rt')ashandle:
forpageiniterpage(handle,1000):
printpage#oryourbusinesslogical
print"-"*32#pagebreak

刪除文本文件的前N行:

defremovehead(filename,headlines):
buffer=[]
withopen(filename,'rt')ashandle:
fori,lninenumerate(handle):
ifln<headlines:
continue
buffer.append(ln)

withopen(filename,'wt')ashandle:
handle.writelines(buffer)

或者:

defgetandremovehead(filename,headlines):
withopen(filename,'rt')ashandle:
buffer=handle.readlines()
withopen(filename,'wt')ashandle:
handle.writelines(buffer[headlines:])
returnbuffer[:headlines]

但遇到大文本文件時,刪除其中N行不是很理想的業務方案

4. python中怎麼刪除文件中指定的行

刪除文件的某一行,可以跳過你要刪除的行進行讀寫,如:

1
2
3
4

data = open(filename, 'rt').readlines()
with open(filename, 'wt') as handle:
handle.writelines(data[:tobedeleted])
handle.writelines(data[tobedeleted+1:])

其中data是逐行讀取文件,

handle.writelines進行讀寫,跳過tobedeleted行

5. python怎麼刪除txt文本裡面的第一行

1、打開python,連接至伺服器。
2、創建一個txt文件,以創建123.txt為例子。
3、敲回車,打開文件,按i,開始輸入文本。保存並退出。
4、再次打開這個文件,可以看到游標是定位在最後一行的下一行位置的。
5、在第一行按dd,就可以刪除當前行。
6、保存並推出之後,再次打開,驗證一下,已經被刪除了。

閱讀全文

與Python刪除文件中第n行行相關的資料

熱點內容
魔鬼訓練程序員 瀏覽:686
php上傳大文件失敗 瀏覽:602
sw伺服器指定埠怎麼填 瀏覽:189
java有哪些數組 瀏覽:984
程序員戴手錶影響工作嗎 瀏覽:235
游戲皇後解壓視頻 瀏覽:367
c語言怎麼打開文件編譯 瀏覽:436
手機上什麼app可以設計logo 瀏覽:800
pid演算法單片機 瀏覽:375
python數據精度 瀏覽:632
管什麼小女孩App 瀏覽:192
phppdf轉換成圖片 瀏覽:468
十八講pdf 瀏覽:619
mysql導入壓縮文件 瀏覽:22
usb控制單片機 瀏覽:906
你為什麼喜歡安卓手機 瀏覽:863
阿里雲伺服器購買和使用 瀏覽:389
單片機sp1 瀏覽:282
大學生玩貓咪解壓 瀏覽:794
php附近的演算法 瀏覽:346