python循环读取文件夹之中的文件并赋给不同的值(循环读取文件 py
Python,将文件中的列表读取出来并作为列表赋给变量
如果是a="[1,2,3,4,5,6,7]",那么可以替换掉方括号,然后用split方法拆分字串
a="[1,2,3,4,5,6,7]"
a=a.replace('[',?'')
a=a.replace(']',?'')
a=map(lambda?i:?int(i),?a.split(','))
python如何实现for循环操作文件?
python用for循环遍历文件操作,代码如下:
#!\urs\bin\env?python
#encoding:utf-8???????#设置编码方式??
import?os
import?re
class?loop_file:
????def?__init__(self,?root_dir,?short_exclude=[],?long_exclude=[],?file_extend=[]):
????????self.root_dir?=?root_dir
????????self.short_exclude?=?short_exclude
????????self.long_exclude?=?long_exclude
????????self.file_extend?=?file_extend
????def?__del__(self):
????????pass
????def?start(self,?func):
????????self.func?=?func
????????return?self.loop_file(self.root_dir)????
????def?loop_file(self,?root_dir):
????????t_sum?=?[]
????????sub_gen?=?os.listdir(root_dir)
????????for?sub?in?sub_gen:
????????????is_exclude?=?False
????????????for?extends?in?self.short_exclude:??##在不检查文件、目录范围中
????????????????if?extends?in?sub:??????????????##包含特定内容
????????????????????is_exclude?=?True
????????????????????break
????????????????if?re.search(extends,?sub):?????##匹配指定正则
????????????????????is_exclude?=?True
????????????????????break????????????????????
????????????if?is_exclude:
????????????????continue????????????
????????????abs_path?=?os.path.join(root_dir,?sub)
????????????is_exclude?=?False
????????????for?exclude?in?self.long_exclude:
????????????????if?exclude?==?abs_path[-len(exclude):]:
????????????????????is_exclude?=?True
????????????????????break
????????????if?is_exclude:
????????????????continue
????????????if?os.path.isdir(abs_path):
????????????????t_sum.extend(self.loop_file(abs_path))
????????????elif?os.path.isfile(abs_path):????????????
????????????????if?not?"."?+?abs_path.rsplit(".",?1)[1]?in?self.file_extend:??##不在后缀名?检查范围中
????????????????????continue
????????????????t_sum.append(self.func(abs_path))
????????return?t_sum????
if?'__main__'==__name__:
????root_dir?=?r'D:\harness\newshoppingcart\testcase\promo\single_promo'
????short_exclude?=?['.svn',?'.*_new.rb']?????###不包含检查的短目录、文件
????long_exclude?=?[]?????????????????????????###不包含检查的长目录、文件
????file_extend?=?['.rb']?????????????????????###包含检查的文件类型
????lf?=?loop_file(root_dir,?short_exclude,?long_exclude,?file_extend)
????for?f?in?lf.start(lambda?f:?f):
????????print?f
python 读取文本并赋值
这个的主要思路是对于字符串进行分割,然后循环读取。
a.txt内容为
telnet_ip=(189.6.68.100,189.6.68.103,189.6.68.105,189.6.68.109,189.6.68.112,189.6.68.123)
user_name=root
代码如下:
def?get_ip(val):??#从(189.6.68.100,189.6.68.103,189.6.68.105,189.6.68.109,189.6.68.112,189.6.68.123)中获取IP,返回一个ip数组
????val?=?val.replace("(",?"")
????val?=?val.replace(")",?"")
????ips?=?val.split(",")
????return?ips
def?main():
????f?=?open?("a.txt","r")
????for?line?in?f:
????????line?=?line.strip()
????????lines?=?line.split("=")
????????key?=?lines[0]
????????if?key.strip()=="user_name":
????????????B?=?lines[1]?#获取user_name
????????elif?key.strip()=="telnet_ip":??
????????????val?=?lines[1]
????????????A?=?get_ip(val)?#获取telnet_ip
????print?"user_name?is?%s?"?%?B
????print?"telnet_ip?is?%s"?%?A
??????????
if?__name__=="__main__":
????main()
Python循环读文件
path = 'your dir'
for dirpath, dirs, files in os.walk(path):
print '1',dirpath
print '2',dirs
print '3',files
for file in files:
z_path = os.path.join(dirpath, file)
print z_path
python txt中的文件,逐行读取,每行赋值给变量
我的方案应该可以完美解决你的问题.首先,你得找一个.txt的文本,我是.ini,都一样,有几行字,我乱敲的,比如:
高分段11返回电视剧kf?方式
客家话?22发vfdg突然
历历可考33t?jyyt
快快乐乐44??
拉开55yt留言
907698076?考虑离开
就付款即可
一UR额也完全
大课间
然后上程序,你只需要改一下你文件的path就可以了
txt,?i=?{},?1
path?=?"C:\\Users\\THINK\Desktop\\3.ini"
f?=?open(path,encoding='utf-8')
for?line?in?f:
????#?print(line)
????txt[i]?=?line
????i?+=?1
????txt.update(txt)
print(txt)
f.close()
#?for?context?in?txt.items():
#?????print(context)
f?=?open(path,'w',encoding='utf-8')
for?k,v?in?txt.items():
????f.write(str(k)+'=?'+v)
f.close()
最后,这个感觉用来写配置文件(参数化)很方便,然后用Python调用.
如果是你说的,把"i += 1" 去掉就,然后把"i=1"换成"i = r"就可以了
如果有用请采纳!!!
另外,转到我新创的CSDN SPACE也有:网页链接
python 循环读一个文件
Python按行读文件
1. 最基本的读文件方法:
# File: readline-example-1.py
file = open("sample.txt")
while 1:
line = file.readline()
if not line:
break
pass # do something
一行一行得从文件读数据,显然比较慢;不过很省内存。
在我的机器上读10M的sample.txt文件,每秒大约读32000行
2. 用fileinput模块
# File: readline-example-2.py
import fileinput
for line in fileinput.input("sample.txt"):
pass
写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多……
3. 带缓存的文件读取
# File: readline-example-3.py
file = open("sample.txt")
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
这个方法真的更好吗?事实证明,用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!
————————————————————————————————————————————————————————————
在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据:
# File: readline-example-5.py
file = open("sample.txt")
for line in file:
pass # do something
而在Python 2.1里,你只能用xreadlines迭代器来实现:
# File: readline-example-4.py
file = open("sample.txt")
for line in file.xreadlines():
pass # do something