'I want to make it so file.write() only writes on that line if that line has nothing written on it [duplicate]
def password_generator():
"code to generate a password here"
file = open('/Users/benkollmar/Desktop/Projects/Passwords', 'w')
file.write(password_sentence)
Every time I call this function it writes what I want in the new file on the first line but I want to add an if statement so it only writes on the line if that line is empty. And if that line is not empty write password_sentence on the next empty line.
Solution 1:[1]
You should use with open() because it automatically closes the file when your done.
You can see that I used 'a' here. That means append, which means add to the end of the file. Finally, adding a \n at the end of your content forces anything appended after it later to be on a different line.
with open(passwordsFile, 'a') as file:
file.write(password_scentence + '\n')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Charles Duffy |
