How do I start reading a file from the top in python? -
i trying add together dependencies list requirements.txt file depending on platform software going run. wrote next code:
if platform.system() == 'windows': # add together windows requirements platform_specific_req = [req1, req2] elif platform.system() == 'linux': # add together linux requirements platform_specific_req = [req3] open('requirements.txt', 'a+') file_handler: requirement in platform_specific_req: already_in_file = false # create sure requirement not in file line in file_handler.readlines(): line = line.rstrip() # remove '\n' @ end of line if line == requirement: already_in_file = true break if not already_in_file: file_handler.write('{0}\n'.format(requirement)) file_handler.close()
but happening code when sec requirement going searched in list of requirements in file, for line in file_handler.readlines():
seems pointing lastly element of list in file new requirement compared lastly element in list, , if not same 1 gets added. causing several elements duplicated in list, since first requirement beingness compared against elements in list. how can tell python start comparing top of file again?
solution: received many great responses, learned lot, guys. ended combining 2 solutions; 1 antti haapala , 1 matthew franglen one. showing final code here reference:
# append requirements requirements.txt file open('requirements.txt', 'r') file_in: reqs_in_file = set([line.rstrip() line in file_in]) missing_reqs = set(platform_specific_reqs).difference(reqs_in_file) open('requirements.txt', 'a') file_out: req in missing_reqs: file_out.write('{0}\n'.format(req))
you open file handle before iterating on existing requirement list. read entire file handle each requirement.
the file handle finish after first requirement because have not reopened it. reopening file each iteration wasteful - read file list , utilize within loops. or set comparison!
file_content = set([line.rstrip() line in file_handler]) only_in_platform = set(platform_specific_req).difference(file_content)
python
No comments:
Post a Comment