1.python中readline()怎么用,还有readline和readlines,read的区别和
python中readline()是用来读取文本文件中的一行。
readline和readlines,read都是用来读取文件内容,readline()每次读取一行,当前位置移到下一行;readlines()读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素;read(size)从文件当前位置起读取size个字节(如果文件结束,就读取到文件结束为止),如果size是负值或省略,读取到文件结束为止,返回结果是一个字符串。 f=open("myfile") while True: line=f.readline() if line: print line, else: break f=open("myfile") lines=f.readline() #lines是一个列表变量 f=open("myfile") lines=f.read() #lines是一个字符串变量。
2.python如何忽略文件的第一行,然后统计剩下部分中某个字符串的
f = open("foo。
txt") ? ? ? ? ? ? # 打开文件 line = f。readline() ? ? ? ? ? ? # 读第一行 line = f。
readline() ? ? ? ? ? ? # 读第二行 ct=0; ? ? ? ? ? ? ? ? ? ? ? ? ? # 计数 while line: ? ?line = f。 readline() ? ?ct =line。
count("name") ? ? ?# 逐行统计,要找的字串为name f。close() print (ct) ? ? ? ? ? ? ? ? ? ? ?#输出结果 追答 : 有个小问题,while中两句写反了,正确的f = open("foo。
txt") # 打开文件 line = f。readline() # 读第一行line = f。
readline() # 读第二行ct=0; # 计数 while line: ct =line。 count("name") # 逐行统计,要找的字串为name line = f。
readline()f。close()print (ct) #输出结果。
3.怎么在.py程序中进入python的交互模式
IPython 进入方法:
from IPython import start_ipython
start_ipython()
bpython 进入方法:
import bpython
bpython.embed()
需要另外安装第三方扩展。
而且自己写一个简单的也费不了几行:
import traceback, sys
def magic():
while True:
cmd = sys.stdin.readline()
if not cmd:
continue
try:
exec(cmd)
except Exception as err:
if isinstance(err, KeyboardInterrupt):
break
traceback.print_last()
magic()
转载请注明出处编程代码网 » readline()python