As explained in my Summer of code 2017: Python post I decided to pick up Python
This is officially day 23. today I will take a look at files
First lets take a look at the open() function, you need to pass in the path, everything else is optional
You should always pass in the mode for clarity
Character | Meaning |
---|---|
'r' |
open for reading (default) |
'w' |
open for writing, truncating the file first |
'x' |
open for exclusive creation, failing if the file already exists |
'a' |
open for writing, appending to the end of the file if it exists |
'b' |
binary mode |
't' |
text mode (default) |
'+' |
open a disk file for updating (reading and writing) |
'U' |
universal newlines mode (deprecated) |
Writing to a file in Python
Here is an example of how to write to a file
f = open('boo.txt', mode ='wt', encoding='utf=8') f.write('the first line') f.write('line 2\n') f.write('line 3') f.write('line 4') f.close()
Here is what the file looks like after running the example above
As you can see if you don't supply line breaks, there won't be any line breaks in the file, this is why there is only 1 line break in the file
If you run the same example again, the same exact file will be created, this is because mode w will truncate the file first
If you change the mode from wt to at, then the text will be appended
f = open('boo.txt', mode ='at', encoding='utf=8') f.write('the first line') f.write('line 2\n') f.write('line 3') f.write('line 4')
Reading a file in Python
Reading files is similar to writing files, you still use open and specify mode and encoding
To read the first 10 characters, you can specify read(10)
If you want to read the whole file, you can just specify read(), if you specify read() again, you will get back an empty string. To start reading from the beginning again, you can use seek(0)
To read a line at a time, use readline()
Here is how all this above looks inside the REPL
>>> f = open('boo.txt', mode ='rt', encoding='utf=8') >>> f.read(10) 'the first ' >>> f.read() 'lineline 2\nline 3line 4the first lineline 2\nline 3line 4the first lineline 2\nline 3line 4' >>> f.read() '' >>> f.seek(0) 0 >>> f.readline() 'the first lineline 2\n' >>> f.readline() 'line 3line 4the first lineline 2\n' >>> f.readline() 'line 3line 4the first lineline 2\n' >>> f.readline() 'line 3line 4' >>> f.readline() ''
That is all for today, short and sweet....
No comments:
Post a Comment