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())
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 :)
+ 1
Thanks š®š³Omkarš , i got the point š®