老师为什么我的结果是把每次循环的结果都打印出来了呢
来源:1-5 文件的读操作
慕尼黑1183503
2022-05-31 22:44:10

# coding-utf-8
import os
def open_package(path):
if os.path.exists(path):
raise Exception('%s路径已经存在' % path)
os.makedirs(path)
init_path = os.path.join(path, '__init__')
f = open(init_path, 'w')
f.write('# coding-utf-8\n')
class Open(object):
def __init__(self, path, mode= 'w', is_return = True):
self.path = path
self.mode = mode
self.is_return = is_return
def write(self, message):
f = open(self.path, self.mode)
if self.is_return:
f.write('%s\n' % message)
f.close()
def read(self, is_strip=True):
result = []
with open(self.path, mode=self.mode) as f:
data = f.readlines()
for line in data:
if is_strip == True:
temp = line.strip()
if temp != "":
result.append(temp)
print(result)
else:
if line != '':
result.append(line)
return result
if __name__ == '__main__':
current_path = os.getcwd()
# path = os.path.join(current_path, 'test2')
# open_package(path)
open_path = os.path.join(current_path, 'b.txt')
o = Open('package_time.py', mode='r')
# o.write('你好,小慕')
o.read()1回答
好帮手慕小猿
2022-06-01
同学,你好!输出多次值,是因为在for 循环中使用print(result)输出,每循环一次,便会输出打印一次,同学可以将print(result)语句注释,如图:

可以在调用read()方法时将返回的结果赋值给变量并输出该变量的值,如图:

祝学习愉快~
相似问题