導航:首頁 > 編程語言 > 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行行相關的資料

熱點內容
字幕網app怎麼找 瀏覽:528
奧迪a4l壓縮比 瀏覽:693
iis7伺服器怎麼安裝 瀏覽:975
孩子上學壓力太大怎麼解壓 瀏覽:236
javaurl格式 瀏覽:342
勻稱app怎麼用 瀏覽:61
pythonemail中文亂碼 瀏覽:442
android訪問html 瀏覽:88
做一個app或者網頁用什麼編程 瀏覽:776
一體機伺服器運行失敗怎麼辦 瀏覽:936
longjava比較大小 瀏覽:531
clojure編程pdf 瀏覽:22
一年級數學圈一圈的演算法 瀏覽:111
完整的python 瀏覽:42
c51單片機數字鍾 瀏覽:923
apk文件反編譯後安裝包損壞 瀏覽:816
app圖標分別是什麼 瀏覽:368
linux全選命令 瀏覽:365
怎麼用華碩app 瀏覽:963
小明台灣通道加密 瀏覽:376