Python 3 Files - Opening & Reading

Python 3: From Scratch to Intermediate INTERMEDIATE LEVEL: Python 3 - File Operations
12 minutes
Share the link to this page
Copied
  Completed
You need to have access to the item to view this lesson.
One-time Fee
$99.99
List Price:  $139.99
You save:  $40
€93.80
List Price:  €131.33
You save:  €37.52
£80.29
List Price:  £112.41
You save:  £32.12
CA$137.56
List Price:  CA$192.59
You save:  CA$55.03
A$155.72
List Price:  A$218.02
You save:  A$62.29
S$136.13
List Price:  S$190.59
You save:  S$54.46
HK$783.15
List Price:  HK$1,096.44
You save:  HK$313.29
CHF 90.82
List Price:  CHF 127.16
You save:  CHF 36.33
NOK kr1,103.56
List Price:  NOK kr1,545.03
You save:  NOK kr441.46
DKK kr700
List Price:  DKK kr980.03
You save:  DKK kr280.02
NZ$169.65
List Price:  NZ$237.52
You save:  NZ$67.86
د.إ367.23
List Price:  د.إ514.13
You save:  د.إ146.90
৳10,973.26
List Price:  ৳15,363.01
You save:  ৳4,389.74
₹8,346.81
List Price:  ₹11,685.87
You save:  ₹3,339.05
RM478.30
List Price:  RM669.64
You save:  RM191.34
₦129,687.03
List Price:  ₦181,567.03
You save:  ₦51,880
₨27,846.09
List Price:  ₨38,985.64
You save:  ₨11,139.55
฿3,684.97
List Price:  ฿5,159.11
You save:  ฿1,474.13
₺3,259.29
List Price:  ₺4,563.14
You save:  ₺1,303.85
B$524.14
List Price:  B$733.82
You save:  B$209.68
R1,920
List Price:  R2,688.08
You save:  R768.07
Лв183.64
List Price:  Лв257.10
You save:  Лв73.46
₩138,024.19
List Price:  ₩193,239.39
You save:  ₩55,215.20
₪378.55
List Price:  ₪529.99
You save:  ₪151.43
₱5,756.02
List Price:  ₱8,058.66
You save:  ₱2,302.64
¥15,447.20
List Price:  ¥21,626.70
You save:  ¥6,179.50
MX$1,726.94
List Price:  MX$2,417.79
You save:  MX$690.84
QR366.07
List Price:  QR512.51
You save:  QR146.44
P1,385.95
List Price:  P1,940.39
You save:  P554.43
KSh13,348.66
List Price:  KSh18,688.66
You save:  KSh5,340
E£4,832.56
List Price:  E£6,765.78
You save:  E£1,933.22
ብር5,710.80
List Price:  ብር7,995.35
You save:  ብር2,284.55
Kz83,585.80
List Price:  Kz117,023.47
You save:  Kz33,437.66
CLP$96,622.33
List Price:  CLP$135,275.13
You save:  CLP$38,652.80
CN¥724.04
List Price:  CN¥1,013.69
You save:  CN¥289.64
RD$5,929.75
List Price:  RD$8,301.89
You save:  RD$2,372.13
DA13,457.15
List Price:  DA18,840.55
You save:  DA5,383.40
FJ$227.57
List Price:  FJ$318.61
You save:  FJ$91.03
Q780.47
List Price:  Q1,092.69
You save:  Q312.22
GY$20,930.40
List Price:  GY$29,303.40
You save:  GY$8,372.99
ISK kr14,100.58
List Price:  ISK kr19,741.38
You save:  ISK kr5,640.80
DH1,016.63
List Price:  DH1,423.32
You save:  DH406.69
L1,790.82
List Price:  L2,507.22
You save:  L716.40
ден5,785.11
List Price:  ден8,099.38
You save:  ден2,314.27
MOP$806.50
List Price:  MOP$1,129.14
You save:  MOP$322.63
N$1,910.91
List Price:  N$2,675.35
You save:  N$764.44
C$3,692.82
List Price:  C$5,170.09
You save:  C$1,477.27
रु13,360.74
List Price:  रु18,705.58
You save:  रु5,344.83
S/376.13
List Price:  S/526.61
You save:  S/150.47
K381.31
List Price:  K533.85
You save:  K152.54
SAR375.08
List Price:  SAR525.14
You save:  SAR150.05
ZK2,557.08
List Price:  ZK3,580.02
You save:  ZK1,022.93
L466.85
List Price:  L653.61
You save:  L186.76
Kč2,369.96
List Price:  Kč3,318.04
You save:  Kč948.08
Ft37,031.68
List Price:  Ft51,845.84
You save:  Ft14,814.15
SEK kr1,094.85
List Price:  SEK kr1,532.83
You save:  SEK kr437.98
ARS$86,967.11
List Price:  ARS$121,757.44
You save:  ARS$34,790.32
Bs693.40
List Price:  Bs970.79
You save:  Bs277.38
COP$389,858.15
List Price:  COP$545,817.01
You save:  COP$155,958.85
₡50,274.61
List Price:  ₡70,386.47
You save:  ₡20,111.85
L2,477.26
List Price:  L3,468.26
You save:  L991
₲742,412.64
List Price:  ₲1,039,407.40
You save:  ₲296,994.75
$U3,872.48
List Price:  $U5,421.62
You save:  $U1,549.14
zł405.79
List Price:  zł568.12
You save:  zł162.33
Already have an account? Log In

Transcript

Python provides all the tools you need for handling files in your operating system. You can open and read files, you can write or append to a file, and also store and use the information within a file into your application. As you do with any file in your file system, whether it is a Word document, a picture or a video, you first have to open the file in order to read or modify its contents. For this, Python provides you with the open function. You are not required to import any modules to be able to use all the file methods that Python provides to the user. Let's first create a txt file on the D drive and insert some data into the file.

And then we will start playing around with this file. I have already created a file called routers dot txt, having the names of some networking vendors as its content Now it's time to create a file object and read it. This is how you can do this. Let's open the Python interpreter and start working with files. First, you should type in a name for the file object, you create, let's say my file, then the equal sign, and then you will use the open function. So my file equals open.

Let me write this in. So we have open and in between parentheses, you first specify the name of the file you want to open, and the path to that file enclosed by double quotes. So here is the path to my file right here. Then separated by a comma, you enter the access mode in which you want the file to be opened, also enclosed by double quotes. So let's open the file for reading. For this we will use the our access mode.

The most common mode in which you can open a file are are for reading. Keep in mind that this is the default mode. So if you don't type in R when opening a file, Python will open it for reading by default. The second mode is W for writing, and then we have a for appending to the end of the file, you may also encounter B as a file access mode. This stands for binary format, and it is used when playing around with binary files, like photos, Adobe PDFs, executable files and so on. The binary mode should be used for all files that don't contain text.

Finally, we have the x mode available, which stands for exclusive creation. This clearly means that you will use this mode for exclusively creating the file and fails if the file already exists. Basically, this is the same as using the W access mode. Only it raises an exception if the file already exists. I will provide a complete list of file opening modes at the end of this section. So you Have it at hand, whenever you are in doubt about using a certain access mode.

If you want to check the mode in which a file has been opened, you can check out an attribute named mode for your file. So let me hit Enter. And now you can type in my file dot mode. So again, we see that our file is currently open for reading. Now having the file open, let's see how to access and print out the data within the file. Python provides three important methods to read data from a file.

The first method is called read, which returns the entire content of a file in the form of a string. So let's try my file dot read, open and close parentheses. So you can see that we have all the vendors listed inside a single string separated by the newline character, the backslash n, all the although not very estatic. This may be useful for searching some thing inside the entire file, or maybe matching some text patterns inside the file. We will talk more about patterns and regular expressions later in the course. One more thing about the read method is that you can tell Python to read only a number of bytes from the file and return that many characters, not the entire contents of the file.

You can do this by entering an integer in between the parentheses of read. Let's say you want only Cisco to be returned from within our file. This means the first five characters in the file, right? That would mean my file dot read a five. Wait a minute, this doesn't return what it should. Did I lie when I said it will return the first five characters in the file?

Well, no I didn't. This is where the concept of cursor enters the game. The cursor is the position at which you are currently located inside the file. So after we previously read the file, the entire file using the Read method, we are now positioned at the end of the file. That's why nothing is returned. When we want to read the file content further.

At this point, we actually have nothing else to read, we already went through all the text in the file. To go back to the beginning of the file, you have to position the cursor before the first character. You can do this using the seek method, where in between the parentheses of seek you enter the position or better set the number of bytes from the beginning of the file at which you want the cursor to be positioned. If you want to start from the very beginning, you will use seek of zero. So let's use this my file dot seek of zero. This also returns the new position at which the cursor is currently positioned.

Furthermore, to see the current position of your cursor, you can also use the tail method and it should return the same result. So my file dot tell also read Turns zero, this shows that we are currently positioned at zero bytes from the beginning of the file, just what we were looking to achieve. Now we can read the file again, remember, we wanted to read only the first five characters or bytes in the file. So let's use the my file dot read of five command again. And this time we got Cisco returned, which is indeed correct. Another useful method is read the line.

This method returns the file content line by line one line at a time, each time you call the method. Let's see this in practice. But first, let's go back to the beginning of the file, once again, using my file dot seek of zero. Now let's use my file dot read line, open and close parentheses. And we get Cisco and backslash and the first row in the file. Let me move this over so you can see the file better.

Now the next time we use the redline method, we get the next row in the file which is Juniper and let's go through all the rows. So we got each line of the file printed out, and then in the end, we got an empty string. As you can see right here, this signals that we have reached the end of the file. The third way of reading files is using the read lines method. This method returns a list where each element of the list is a line in the file. This method is very useful for iterating over a file, and it is frequently used when working with strings.

So let's go back to the beginning of the file using my file dot seek of zero. Okay, and now let's use the read lines method, my file dot read lines, open and close parentheses. And as you can see, we got the list I was talking about. Now you can use a for loop to work with the elements of this list. First, of course, don't forget about the seek method. If you forget to position the cursor at the very beginning of the file, then you will end up with an empty list when calling the read lines method again.

So let me prove this to you. If we use read lines again, we indeed get an empty list. That's the proof. Now, as I said, Let's use the seek method once again. And now let's print out the vendors whose names start with a capital A. For this, we are going to iterate over the list provided by the read lines method, and use a condition stating that if the list element, which is a string, starts with a capital A, then go ahead and print that element to the screen.

So this would be for line in my file, dot read lines, open close parentheses, colon, if line dot. And now remember, the starts with method starts with a colon, then print line, Enter. And indeed, we have a name error because instead of the string a, we enter just a m Python things that this is a variable that should have been defined. For this reason, I'm going to change my code because we are looking for the vendors starting with a letter. So that would be a string, I just have to add in the double quotes, right here. Now let's hit enter twice.

And we are looking for vendors starting with a capital A, not a lowercase a. So let's try this again, let's run our code. We're still not getting the result we're looking for. Why is that? Well, because while changing our code and trying different versions of this for loop, we've already gone through the entire file. And we haven't used the seek methods to go back to the beginning of the file.

So let's do that. My file dot seek of zero. And finally, I promise you that this time, this will work, enter and indeed we get a via and Arista as expected. I think this was a great moment for you to exercise your attention to details when writing code. Okay, notice here that we are So got a blank line after each string. So a blank line after Avaya and another one after Arista, that's because we had a backslash n a newline character at the end of each element in the list, right?

Let's also test the x mode on our already existing file, and see if it really generates an exception, since the routers dot txt file already exists. So let's try my file equals open. And let's use the x mode. Okay, so here's our confirmation about the x axis mode. And its associated exception file exists error file exists, and this is the name of the file and the path to the file. Okay, but what if the file does not exist?

That means we should have a new file created, right? Let's test this as well. So let's try routers to dot txt this time, okay. And now if we check fd, we can see that a new file called router's two dot txt has been created. Okay, one thing to keep in mind here, depending on your current system setup and the type of privileges that you have, as a user, you might end up with a permission error if the user you're currently logged in with has no administrative privileges, and thus cannot save to the C drive or D drive or whatever location you choose. So also be very careful at the privileges that you have as a user in your operating system.

However, if you are already an administrator on your Windows operating system, then you're good to go. On the other hand, if you're not an administrator on your local operating system, the solution is either to change the location where you want to create a new file to another drive or to the desktop, for example, or to open up another Python interpreter, run it as an administrator this time to do this just right click on the interpreters icon and Select run as administrator, then click Yes. But again if you are already an administrator, you don't have to worry about this at all.

Sign Up

Share

Share with friends, get 20% off
Invite your friends to LearnDesk learning marketplace. For each purchase they make, you get 20% off (upto $10) on your next purchase.