0

Can you make it in better manner?

we have a list of names,--names=['John' ,' Oscar' , 'jacob'] write this list in a file. and out put should be? John Oscar Jacob My Code is:(which seams not very good) names = ["John", "Oscar", "Jacob"] name=str() for name in names: file = open("names.txt", "w+") file.write(name) file.close() file= open("names.txt", "r") print(file.read())

14th Aug 2020, 6:28 AM
Abhishek
2 Answers
+ 3
``` names = ["John", "Oscar", "Jacob"] # name=str() not required file = open("names.txt", "w+") file.write("\n".join(names)) file.close() file = open("names.txt", "r") print(file.read()) ``` *What I did : 1.name = str() was not required , commented it 2.removed for loop, using join method of `str` to concat element with `\n` (newline charecter) 3. first write all words and then read all words instead of opening and closing file for each word. I don't usually write codes in python, There are maybe better ways :)
14th Aug 2020, 7:15 AM
šŸ‡®šŸ‡³OmkaršŸ•‰
šŸ‡®šŸ‡³OmkaršŸ•‰ - avatar
+ 1
Thanks šŸ‡®šŸ‡³OmkaršŸ•‰ , i got the point šŸ‡®
14th Aug 2020, 12:40 PM
Abhishek