如何在Python 3中使用面向对象编程读取文本文件
如何在Python 3中使用面向对象编程读取文本文件,python,python-3.x,oop,object,Python,Python 3.x,Oop,Object,我试图使用一个新类和OOP来读取Python中的文本文件,但是如果不使用像这样的命令式编程,我就找不到正确的方法 def read_operators_file(file_name): in_file=open(file_name) for i in range(constants.HEADER_TOTAL_LINES): in_file.readline() operators=[] for line in
我试图使用一个新类和OOP来读取Python中的文本文件,但是如果不使用像这样的命令式编程,我就找不到正确的方法
def read_operators_file(file_name):
in_file=open(file_name)
for i in range(constants.HEADER_TOTAL_LINES):
in_file.readline()
operators=[]
for line in in_file:
name, nationality, domain, hours, duration = line.strip().split(', ')
duration=int(duration)
domain=tuple(domain.strip('(').strip(')').split('; '))
operators.append((name, nationality, domain, hours, duration))
in_file.close()
return operators
def read_requests_file(file_name):
in_file = open(file_name)
for i in range(constants.HEADER_TOTAL_LINES):
in_file.readline()
requests = []
for line in in_file:
name, language, domain, service, duration = line.strip().split(', ')
duration = int(duration)
requests.append((name, language, domain, service, duration))
in_file.close()
return requests
谢谢,mikeysantana虽然您当然可以将其转换为OOP风格,但我认为这不会有多大帮助。相反,我建议尝试一种风格。您可以定义另一个函数,将不同的转换函数作为参数,例如,
str
基本上没有操作,int
,或者对于更复杂的内容,使用lambda
。此外,您还应使用和
来打开文件
类似于此(未经测试):
或使用生成器功能:
def read_fields(file_name, functions):
with open(file_name) as in_file:
for i in range(constants.HEADER_TOTAL_LINES):
in_file.readline()
for line in in_file:
yield from (f(x) for f, x in zip(functions) line.strip().split(', '))
您当然可以将这些函数封装在一个类中,但是使用类有什么好处呢?您需要一些状态才能在调用之间生存吗?
def read_fields(file_name, functions):
with open(file_name) as in_file:
for i in range(constants.HEADER_TOTAL_LINES):
in_file.readline()
for line in in_file:
yield from (f(x) for f, x in zip(functions) line.strip().split(', '))