file1 = open("test.txt")
file2 = open("output.txt", "w")
while True:
line = file1.readline()
file2.write('"' + line+'"')
if not line:
break
file1.close()
file2.close()
read()将文本文件所有行读到一个字符串中
readline()是一行一行的读
readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素
#文件迭代器
file2 = open("output.txt", "w")
for line in open("test.txt"):
file2.write('"'+line+'"')
#文件上下文管理器
with open('somefile.txt', 'r') as f:
data = f.read()
with open('somefile.txt', 'r') as f:
for line in f:
with open('somefile.txt', 'w') as f:
f.write(text1)
f.write(text2)
...
with open('somefile.txt', 'w') as f:
print(line1, file=f)
将变量从内存中变成可以存储或传输的过程称为序列化,在Python中叫做pickling,在其他语言中也称为serialization、marshaling、flattening等等。反之,则为反序列化,称为unpickling,把变量内存从序列化的对象重新读取到内存中。
# 序列化
import pickle
d = dict(name = '思聪', age = 29, score = 80)
str = pickle.dumps(d) #调用pickle的dumps函数进行序列化处理
print(str)
f = open('dump.txt', 'wb')
pickle.dump(d, f)
f.close()
# 反序列化
import pickle
f = open('dump.txt', 'rb')
d = pickle.load(f)
f.close()
print(d)
print('name is %s' % d['name'])
python使用lambda来创建匿名函数
Lambda函数只包含一个语句, 如下:
lambda [arg1 [,arg2,...argn]]:expression
sum = lambda arg1, arg2: arg1 + arg2
sum(10, 20)
def sum(arg1, arg2):
return arg1 + arg2
#filter
l = [100, 20, 24, 50, 110]
new = list(filter(lambda x: x<50, l))
print(new) # [20, 24]
近期评论