I'm very new to programming/python so I have some trouble understanding in which order different operations should be performed for optimal usage. I wrote a script that takes a long list of words and searches different files for bits of text that contain these words and returns the result but it is not very fast at the moment.
What I think I first need to optimize is the code listed below. Is there a more resource efficient way to write the following code:
ListofStuff = ["blabla", "singer", "dinger"]
def FindinFile(FindStuff):
with open(File, encoding="utf-8") as TargetFile:
for row in TargetFile:
# search whole file for FindStuff and return chunkoftext as result
def EditText(result):
#do some text editing to result
print edited text
for key in ListofStuff:
EditText(FindinFile(key))
Does (with open) here open the file each time I rerun the function FindinFile in the for-loop at the end? Or does (with-open) keep the file in the buffer until the script is finished?
You have to assume that variable is valid and exists in the same scope in which it was defined. It was defined in a with
clause, so it ceases to exist once you exit this clause (and function) - so yes, file is reopened every that time (unless there's some optimization, which is unlikely in this case, though).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.