导航:首页 > 编程语言 > 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给文件每一行加行号相关的资料

热点内容
pythonimportsys作用 浏览:276
腾讯云拼团云服务器 浏览:364
海南离岛将加贴溯源码销售吗 浏览:244
linux分区读取 浏览:794
单片机液晶显示屏出现雪花 浏览:890
解压器用哪个好一点 浏览:771
什么app看小说全免费 浏览:503
sha和ras加密 浏览:823
韩顺平php视频笔记 浏览:636
阿里云ecs服务器如何设置自动重启 浏览:596
三星电视怎么卸掉app 浏览:317
如何将pdf转换成docx文件 浏览:32
dos命令批量改名 浏览:376
centosphp环境包 浏览:602
mfipdf 浏览:534
电脑解压后电脑蓝屏 浏览:295
外网访问内网服务器如何在路由器设置 浏览:856
2014统计年鉴pdf 浏览:434
linuxoracle用户密码 浏览:757
股票交易pdf 浏览:898