-
Notifications
You must be signed in to change notification settings - Fork 0
Files
natalie363 edited this page Nov 10, 2022
·
3 revisions
- read()
- write() - be careful when writing to files because it will overwrite if there's already data in the file
- append()
- open()
- close()
- If you use the open() function, you must remember to close the file when you are done with it.
- Instead you can use the syntax with open('filename','operation') as f. You indent the relevant lines, and it closes the file when the indent ends
- The operation options are write, read, or append, entered as w, r, or a
- There's also r+ which reads and writes
- You can find the mode with the function f.mode
- Similarly, you can find the name with f.name
- You can use any letter in place of f, f is typically used because f stands for file
- Can read the file, then use an if statement to find out if file exists - if the file content is not equal to null, then you should append, if it is null, then you can write
- If it exists, you want to append
- f = open('filename', 'a')
- f.write('Text to Append')
- If not, you can write to it without overwriting anything
- f = open('filename', 'w')
- f.write('Text to Write')