The best way to deal with large files in Python style
2015-04-07 15:00
495 查看
<span style="font-family:Arial Black;font-size:12px;color:#000099;">with open(...) as f: for line in f: <do something with line></span>
The
withstatement handles opening and closing the file, including if an exception is raised in the inner block. The
for line in ftreats the file object
fas an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files.
Click
here for origin.
Another alternative: by making use of
yield.<span style="font-family:Arial Black;font-size:12px;">def read_file(fpath):
BLOCK_SIZE = 1024with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return</span>Click
here for origin.
相关文章推荐
- The best way to get unique elements of a list in Python
- Python: Best Way to Exchange Keys with Values in a Dictionary?
- Python: Best Way to Exchange Keys with Values in a Dictionary?
- What's the best way to hide a tab in a TabNavigator?
- ADF: The best way to indicate for records in a table the existence of details
- how to deal with the situation that the language support option disappears in linux ubuntu
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- What is the best way to paginate results in SQL Server
- 【引】How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
- the best description to SYS module in python
- The Best Way to Use a 32-Bit DLL Library in a 64-Bit Platform
- The best way to Outfit Rich in Junior high school
- The easy way to execute sudo command in Python using subprocess.Popen
- What is the best way to handle Invalid CSRF token found in the request when session times out in Spring security
- Vagrant is attempting to interface with the UI in a way that requires a TTY
- How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
- What 's CATT(Computer Aided Test Tool)?How to deal with the CATT in the SAP System?什么是CATT(计算机附加测试工具)
- How to deal with the "ErrorWebPart" error displayed in the web part maintenance page
- What's the best way to define a class in javascript
- The Best Way to Unit Test in Android