導航:首頁 > 編程語言 > python給文件每一行加行號

python給文件每一行加行號

發布時間:2022-04-25 02:52:24

python中怎麼列印行號和文件名

通過調用堆棧裡面的代碼對象來獲取。

一般是自己引發一個異常,然後捕獲這個異常,在異常處理中通過堆棧信息獲得行號。

比如:

try:
raiseZeroDivisionError
exceptZeroDivisionError:
frame=sys.exc_info()[2].tb_frame.f_back
returnframe.f_lineno

如果需要更多的信息,可以通過inspect模塊的stack()方法獲得整個調用棧。可自定義一個exception類型。

importinspect
classMyErrorCode(object):
STANDARD=0x0001

code_map_msg={
MyErrorCode.STANDARD:"standarderror",
}
classMyError(Exception):
def__init__(self,error_code):
self.error_code=error_code
try:
_current_call=inspect.stack()[1]
_iframe=_current_call[0]
self.line_no=_iframe.f_lineno
self.mole_name=_iframe.f_globals.get("__name__","")
self.method_name=_current_call[3]
self.class_name=_iframe.f_locals.get("self",None).__class__.__name__
except(IndexError,AttributeError):
self.line_no=""
self.mole_name=""
self.method_name=""
self.class_name=""

def__repr__(self):
msg=code_map_msg.get(self.error_code,"")
return"[*]MyError:%s>%s.mole:%s,class:%s,method:%s,line:%s"%(self.error_code,msg,self.mole_name,self.class_name,self.method_name,self.line_no)

def__str__(self):
returncode_map_msg.get(self.error_code,"notfindanymatchmsgforcode:%s"%self.error_code)

然後在需要獲取行號的地方引發這個異常並捕獲它,然後從異常對象中獲取line_no.

② python的IDLE設置行號

配置起來 不好用
還不如換個 編輯器
比如
Sublime Text
PyCharm

③ python 給txt每句文字加序號

我整個最快的方法
你不是TXT嗎
下載一個Word 2003
吧你要加1.2.3.4.
的所有文件復制粘貼到Word 2003
中 然後CTRL+A 點上面第一排的格式選項在點裡面的項目符號與編號
出來對話框選編號
選一個
確定
你要非要TXT的話 就在全復制CTRL+A 粘貼到TXT文擋上
KO了 給分!謝謝

④ 使用python編程,實現對txt文件中每行內容進行追加。


#-*-coding:utf-8-*-

importre
importos

filepath='E:\data11-20\0.025'
#filepath=os.getcwd()
lst=[]
foriinrange(3,100):
filename='plane1-conv{:03d}.out'.format(i)
fullname=(os.sep).join([filepath,filename])
withopen(fullname)asf:
s=f.read().strip()
lst1=[re.split(r's+',si.strip())[-1]forsiins.split(' ')]
lst.append(lst1)
#lst是一個二維數組,每個文件的最後一列作為一個一維數組存在裡面
#然後找出最長列的長度lmax,其他比它短的數據列,用lmax-len(i)組空格補到和它一樣長
#每組空格的數目等於數據列的第一個數據的長度
lmax=max([len(i)foriinlst])
ws=[i+[''*len(i[0])]*(lmax-len(i))foriinlst]

withopen('E:\hehe.txt','w')aswf:
wf.write(' '.join([''.join(i)foriinws]))

⑤ 關於Python中的一段為Python腳本添加行號腳本

C語言有__LINE__來表示源代碼的當前行號,經常在記錄日誌時使用。Python如何獲取源代碼的當前行號?
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?

exception輸出的函數調用棧就是個典型的應用:
A typical example is the output of function call stack when an exception:

python代碼
File "D:\workspace\Python\src\lang\lineno.py", line 19, in <mole>
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or molo by zero

那麼我們就從錯誤棧的輸出入手,traceback模塊中:
Now that, Let's begin with the output of an exception call stack, in the traceback mole:

python代碼
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.

The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)

def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())

traceback模塊構造一個ZeroDivisionError,並通過sys模塊的exc_info()來獲取運行時上下文。我們看到,所有的秘密都在tb_frame中,這是函數調用棧中的一個幀。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys mole to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.

對,就是這么簡單!只要我們能找到調用棧frame對象即可獲取到行號!因此,我們可以用同樣的方法來達到目的,我們自定義一個lineno函數:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:

python代碼
import sys

def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno

def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()

是否有更方便的方法獲取到frame對象?當然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!

python代碼
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno

類似地,通過frame對象,我們還可以獲取到當前文件、當前函數等信息,就像C語音的__FILE__與__FUNCTION__一樣。其實現方式,留給你們自己去發現。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.

⑥ 如何用python在文件中連續的某幾行開頭添加空格比如我要給第3行到第5行的每行開頭添加兩空格。

writer=open("out.txt","w")
fori,lineinenumerate(open("input.txt")):
if2<=i<=4:
writer.write(""+line)
else:
writer.write(line)
writer.close()

⑦ 請教大家,python編程:怎麼為該程序輸出的每行標上行號:

count = 1
for i in range(1,5):
....for j in range(1,5):
........for k in range(1,5):
............if( i != k ) and (i != j) and (j != k):
................print count,':',i,j,k
............count+=1

⑧ python中向文本每行行尾添加字元

def read_file(file_path="abc.txt"):
file = open(file_path, "r")
content = file.readlines()
file.close()
return content

def write_file(content, file_path="abc1.txt"):
file = open(file_path, "w")
file.writelines(content)
file.flush()
file.close()

if __name__ == "__main__":
content = read_file()
new_content = list()

for c in content:
c = c.strip()
new_content.append(c + str(int(c) - 1) + "\r\n")
write_file(new_content)

⑨ python腳本如何實現給文本中的每一行的行尾加一個固定符號

lines=[]
withopen('test.py','r')asf_in:
forlineinf_in:
line=line[0:-1]+'#'+' '
lines.append(line)

withopen('test.py','w')asf_out:
f_out.writelines(lines)

⑩ python 在文件每一行行首加入一個字元串

file=open('test.txt','r',encoding='utf-8')
lines=file.readlines()
file.close()
file=open('test.txt','w',encoding='utf-8')
fork,vinenumerate(lines):
file.write('%d,%s'%(k,v))
file.close()

閱讀全文

與python給文件每一行加行號相關的資料

熱點內容
解壓包如何轉音頻 瀏覽:447
機明自動編程軟體源碼 瀏覽:325
php埠號設置 瀏覽:540
phperegreplace 瀏覽:319
androidgridview翻頁 瀏覽:537
ssh協議編程 瀏覽:634
如何開我的世界電腦伺服器地址 瀏覽:861
玄關pdf 瀏覽:609
程序員學習論壇 瀏覽:940
程序員的毒雞湯怎麼做 瀏覽:548
安卓怎麼降級軟體到手機 瀏覽:281
雲與伺服器入門書籍推薦產品 瀏覽:636
delphi編程助手 瀏覽:762
電腦遇到伺服器問題怎麼辦 瀏覽:515
加工中心編程結束方法 瀏覽:296
了解什麼是web伺服器 瀏覽:140
面向對象的編程的基本特徵 瀏覽:718
php定時執行任務linux 瀏覽:787
php數組中刪除元素 瀏覽:725
螢石雲伺服器視頻 瀏覽:270