When Reading a File in Python, You Must Specify Two Items
Before proceeding, brand sure you understand the concepts of file path and CWD. If you run into problems, visit the Mutual Pitfalls section at the lesser of this page.
Opening and Closing a "File Object"
As seen in Tutorials #15 and #sixteen, file IO (input/output) operations are done through a file data object. Information technology typically gain as follows:- Create a file object using the open() function. Along with the file name, specify:
- 'r' for reading in an existing file (default; tin can exist dropped),
- 'westward' for creating a new file for writing,
- 'a' for appending new content to an existing file.
- Do something with the file object (reading, writing).
- Close the file object by calling the .close() method on the file object.
myfile = open up('alice.txt', 'r') myfile.close() foo.py
myfile = open up('results.txt', 'westward') myfile.close() myfile = open('results.txt', 'a') myfile.close() foo.py
Reading from a File
OK, we know how to open up and shut a file object. Only what are the actual commands for reading? There are multiple methods.First off,
.read() reads in the unabridged text content of the file as a single string. Below, the file is read into a variable named marytxt, which ends up being a string-type object. Download mary-short.txt and attempt out yourself. >>> f = open('mary-curt.txt') >>> marytxt = f.read() >>> f.shut() >>> marytxt 'Mary had a little lamb,\nHis fleece was white as snowfall,\nAnd everywhere that Mary went,\nThe lamb was certain to get.\due north' >>> type(marytxt) <blazon 'str'> >>> len(marytxt) 110 >>> print marytxt[0] Yard |
>>> f = open up('mary-brusque.txt') >>> marylines = f.readlines() >>> f.close() >>> marylines ['Mary had a piddling lamb,\n', 'His fleece was white as snow,\north', 'And everywhere that Mary went,\northward', 'The lamb was sure to go.\due north'] >>> blazon(marylines) <type 'list'> >>> len(marylines) 4 >>> impress marylines[0] Mary had a little lamb, |
f = open up('bible-kjv.txt') for line in f: if 'smite' in line: print line, f.shut() foo.py
Writing to a File
Writing methods also come in a pair: .write() and .writelines(). Like the corresponding reading methods, .write() handles a single string, while .writelines() handles a listing of strings.Below,
.write() writes a single string each time to the designated output file: >>> fout = open('hullo.txt', 'westward') >>> fout.write('Hello, earth!\due north') >>> fout.write('My proper name is Homer.\n') >>> fout.write("What a beautiful mean solar day we're having.\north") >>> fout.shut() |
>>> tobuy = ['milk\n', 'butter\due north', 'coffee beans\north', 'arugula\n'] >>> fout = open('grocerylist.txt', 'due west') >>> fout.writelines(tobuy) >>> fout.close() |
Common Pitfalls

"No such file or directory" fault
>>> f = open('mary-brusque.txt') Traceback (most recent phone call last): File " |
Entire file content can exist read in but One time per opening
>>> f = open('mary-short.txt') >>> marytxt = f.read() >>> marylines = f.readlines() >>> f.shut() >>> len(marytxt) 110 >>> len(marylines) 0 |
But the string type tin can be written
>>> pi = three.141592 >>> fout = open('math.txt', 'westward') >>> fout.write("Pi's value is ") >>> fout.write(pi) Traceback (most recent call last): File " |
Your output file is empty
This happens to everyone: y'all write something out, open up the file to view, just to find it empty. In other times, the file content may be incomplete. Curious, isn't it? Well, the cause is simple: Yous FORGOT .close(). Writing out happens in buffers; flushing out the concluding writing buffer does non happen until you lot close your file object. ALWAYS REMEMBER TO Shut YOUR FILE OBJECT. (Windows) Line breaks do not bear witness up
If you open up your text file in Notepad app in Windows and see everything in one line, don't be alarmed. Open the same text file in Wordpad or, even better, Notepad++, and you will see that the line breaks are there later all. See this FAQ for details.
robinsonwirave1956.blogspot.com
Source: https://sites.pitt.edu/~naraehan/python2/reading_writing_methods.html
إرسال تعليق for "When Reading a File in Python, You Must Specify Two Items"