批量刪除TXT檔案第一行和最後一行

2021-10-11 05:40:04 字數 1557 閱讀 5906

終於實現了把python用起來,記錄一下,環境為python3.7,看了一些網上的方法,但這總算是乙個不錯的開端。

import os

import os.path

import codecs

#這裡放著你要操作的資料夾名稱

path =

'c:\\users\\rym\\desktop\\金融\\後復權\\後復權a股全\\'

#把e:\get_key\目錄下的檔名全部獲取儲存在files中

files = os.listdir(path.encode(

'ansi'

).decode(

'ansi'))

#用set可以很好的去重,在資料處理的時候經常會被使用到。這裡做初始化

datas =

forfile

in files :

#準確獲取乙個txt的位置,利用字串的拼接

txt_path =

'c:\\users\\rym\\desktop\\金融\\後復權\\後復權a股全\\'

+file

.encode(

'ansi'

).decode(

'ansi'

)#把結果儲存了在contents中

contents = codecs.

open

(txt_path.encode(

'ansi'

).decode(

'ansi'),

'r',encoding=

'ansi'

)#datas的資料清空

datas.clear(

)#把資料add到datas中,可以去重

for content in contents:

iflen

(content)

>2:

'ansi'

).decode(

'ansi'))

iflen

(datas)

>2:

datas.pop(0)

datas.pop(-1

)#去重後新的檔案儲存的路徑

new_txt_path =

'c:\\users\\rym\\desktop\\金融\\後復權\\a股后復權改\\'

+file

.encode(

'ansi'

).decode(

'ansi'

) unique_keywords = codecs.

open

(new_txt_path.encode(

'ansi'

).decode(

'ansi'),

'w', encoding=

'ansi'

)#把datas裡的資料輸出到新生成的txt中

for data in datas:

unique_keywords.write(data)

unique_keywords.close(

)contents.close(

)

php刪除txt檔案最後一行

刪除檔案最後一行 param file path 檔案路徑 public function dellastline file path array pop content fclose file 重新寫入檔案 file fopen file path w fwrite file implode co...

vi中跳到檔案的第一行和最後一行

a 輸入 0 或者 1 回車 b 鍵盤按下 小寫 gg a 輸入 回車 b 鍵盤按下大寫 g c 鍵盤按 shift g 其實和第二種方法一樣 vim快速移動游標至行首和行尾 1 需要按行快速移動游標時,可以使用鍵盤上的編輯鍵home,快速將游標移動至當前行的行首。除此之外,也可以在命令模式中使用快...

php 刪除最後一行,php如何刪除檔案最後一行

摘要 php如何刪除檔案最後一行 php刪除檔案最後一行的方法 首先利用fopen 函式開啟乙個檔案 然後利用fgets 函式逐行讀取檔案,將讀取內容放入陣列中 最後利用array pops 函式刪除陣列中的最後乙個元素即可。array pop 函式刪除陣列中的最後乙個元素。返回陣列的最後乙個值。如...