-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdj.txt
More file actions
48 lines (29 loc) · 1.8 KB
/
Copy pathdj.txt
File metadata and controls
48 lines (29 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
im a good guy
Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available. (We will cover downloading modules later on in the course).
Python has a built-in open function that allows us to open and play with basic file types. First we will need a file though. We're going to use some iPython magic to create a text file!
iPython Writing a File
%%writefile test.txt
Hello, this is a quick test file
Overwriting test.txt
Python Opening a file
We can open a file with the open() function. The open function also takes in arguments (also called parameters). Lets see how this is used:
# Open the text.txt we made earlier
my_file = open('test.txt')
# We can now read the file
my_file.read()
'Hello, this is a quick test file'
# But what happens if we try to read it again?
my_file.read()
''
This happens because you can imagine the reading "cursor" is at the end of the file after having read it. So there is nothing left to read. We can reset the "cursor" like this:
# Seek to the start of file (index 0)
my_file.seek(0)
# Now read again
my_file.read()
'Hello, this is a quick test file'
In order to not have to reset every time, we can also use the readlines method. Use caution with large files, since everything will be held in memory. We will learn how to iterate over large files later in the course.
# Readlines returns a list of the lines in the file.
my_file.readlines()
['Hello, this is a quick test file']
Writing to a File
By default, using the open() function will o