The links.txt file contains 3 links that I'm looping thru. I am trying to write the array onto a separate output.txt file. However, the output ignores the contents first 2 links.
If there is a way to do this without json, I'm open to it.
Current Output in output.txt:
["Addee", "Brian]
Desired Output in output.txt:
["Shenmue", "Addison"]
["Mike", "Todd"]
["Addee", "Brian"]
Current Code:
one = open("links.txt", "r")
for two in one.readlines():
driver.get(two)
sleep(3)
arr1=[element.text for element in driver.find_elements_by_class_name('update_models')]
with open("output.txt", "w") as outfile:
json.dump(arr1, outfile)
My Attempt at a solution:
one = open("links.txt", "r")
for two in one.readlines():
driver.get(two)
sleep(3)
arr1=[element.text for element in driver.find_elements_by_class_name('update_models')]
with open("output.txt", "w") as outfile:
json.dump(arr1 "\n", outfile)
Output for attempt:
json.dump(arr1 "\n", outfile)
TypeError: can only concatenate list (not "str") to list
EDIT: When I printed the array according to the following code:
one = open("links.txt", "r")
for two in one.readlines():
driver.get(two)
sleep(3)
arr1=[element.text for element in driver.find_elements_by_class_name('update_models')]
print(arr1)
I got this output:
["Shenmue", "Addison"]
["Mike", "Todd"]
["Addee", "Brian"]
CodePudding user response:
If I am not wrong, w write the file afresh each time. So, even though I see your json.dump inside the for loop, I think it is over-writing the text for each loop, and that is why you see only the last element list. Try a instead of w which appends instead of writes.
This should work. It should append instead of write afresh for each loop.
with open("output.txt", "a") as outfile:
json.dump(arr1, outfile)
