Presentation is loading. Please wait.

Presentation is loading. Please wait.

FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])

Similar presentations


Presentation on theme: "FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])"— Presentation transcript:

1 FILES

2 open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering]) f = open('/path/to/file', 'r') Once a file is opened and you have one file object, you can get various information related to that file.

3 Opens a file for reading only r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

4 Opens a file for both reading and writing r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

5 Opens a file for writing only w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

6 Opens a file for both writing and reading w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

7 Opens a file for appending a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

8 Opens a file for both appending and reading a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

9 Opens a file for both appending and reading in binary format ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

10 open a file that doesn’t exist If we try to open a file that doesn’t exist, we get an error: >>> mynewhandle = open("wharrah.txt", "r") IOError: [Errno 2] No such file or directory: "wharrah.txt"

11 list of attributes related to file object AttributeDescription file.closedReturns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.nameReturns name of the file.

12

13 close() When you are done reading from or writing to a file you can close() the file and free memory. f.close() After closing a file, attempts to access the file will fail.

14 Reading a file line-at-a-time The readline() method read one line of a file. readline() returns one line of the file as a string with a new line character ( '\n' ) at the end. If readline() returns an empty string, the end of the file has been reached.

15 readline() >>> f.readline() 'This is the first line.\n' >>> f.readline() 'This is the second line.\n' >>> f.readline() …

16 Reading a file line-at-a-time mynewhandle = open("test.txt", "r") while True: # Keep reading forever theline = mynewhandle.readline() # Try to read next line if len(theline) == 0: # If there are no more lines break # leave the loop # Now process the line we’ve just read print(theline, end="") mynewhandle.close()

17 readlines() readlines() methods read multiple lines of a file. readlines() returns all of the lines in a file as a list. Each line in the list will have a newline character ( '\n' ) at the end.

18 Turning a file into a list of lines readlines() returns all of the lines in a file as a list. Each line in the list will have a newline character ( '\n' ) at the end. >>> f.readlines() ['This is the first line\n', 'This is the second line\n']

19 Turning a file into a list of lines f = open("friends.txt", "r") xs = f.readlines() f.close() xs.sort() g = open("sortedfriends.txt", "w") for v in xs: g.write(v) g.close()

20 The read() method will return the contents of the file as a string. Be careful that your computer has enough memory to read the entire file at once. read() accepts an optional parameter called 'size' that restricts Python to reading a specific portion of the file. f.read() Reading the whole file at once

21 f = open("somefile.txt") content = f.read() f.close() words = content.split() print("There are {0} words in the file.".format(len(words))) Notice here that we left out the "r" mode in line 1. By default, if we don’t supply the mode,

22 write() method The write() method takes a string as input and writes it to a file. Other data types must be converted to strings before they can be written to a file. The write() method does not add a newline character ('\n') to the end of the string.

23 write() method >>> data = 'This string will now be written to a file.' >>> f.write(data) 42

24 Writing our first file

25

26

27 directory we’re assuming that the file somefile.txt is in the same directory as your Python source code. If this is not the case, you may need to provide a full or a relative path to the file. On Windows, a full path could look like "C:\\temp\\somefile.txt", while on a Unix system the full path could be "/home/jimmy/somefile.txt".

28 Working with binary files Files that hold photographs, videos, zip files, executable programs, etc. are called binary files: they’re not organized into lines, and cannot be opened with a normal text editor. Python works just as easily with binary files, but when we read from the file we’re going to get bytes backrather than a string.

29 Here we’ll copy one binary file to another: f = open("somefile.zip", "rb") g = open("thecopy.zip", "wb") while True: buf = f.read(1024) if len(buf) == 0: break g.write(buf) f.close() g.close()

30 Working with binary files we added a "b" to the mode to tell Python that the files are binary rather than text files. In line 5, we see read can take an argument which tells it how many bytes to attempt to read from the file. Here we chose to read and write up to 1024 bytes on each iteration of the loop. When we get back an empty buffer from our attempt to read, we know we can break out of the loop and close both the files. If we set a breakpoint at line 6, (or print type(buf) there) we’ll see that the type of buf is bytes.

31 write binary

32

33 Filter Program Many useful line-processing programs will read a text file line-at-a-time and do some minor processing as they write the lines to an output file. They might number the lines in the output file, or insert extra blank lines after every 60 lines to make it convenient for printing on sheets of paper, or extract some specific columns only from each line in the source file, or only print lines that contain a specific substring. We call this kind of program a filter.

34 A filter that copies one file to another 1 def filter(oldfile, newfile): 2 infile = open(oldfile, "r") 3 outfile = open(newfile, "w") 4 while True: 5 text = infile.readline() 6 if len(text) == 0: 7 break 8 if text[0] == "#": 9 continue 10 11 # Put any more processing logic here 12 outfile.write(text) 13 14 infile.close() 15 outfile.close()

35 Directories When we create a new file by opening it and writing, the new file goes in the current directory (wherever we were when we ran the program). Similarly, when we open a file for reading, Python looks for it in the current directory.

36 Directory If we want to open a file somewhere else, we have to specify the path to the file, which is the name of the directory (or folder) where the file is located: >>> wordsfile = open("c:/temp/words.txt", "r") >>> wordlist = wordsfile.readlines() >>> print(wordlist[:6]) [’\n’, ’A\n’, "A’s\n", ’AOL\n’, "AOL’s\n", ’Aachen\n’]

37


Download ppt "FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])"

Similar presentations


Ads by Google