python 如何读取超大的文件
在 Python 中读取超大的文件(例如,文件的大小大于系统内存)时,通常需要逐行或分块读取,以避免将整个文件加载到内存中,从而导致内存不足的问题。以下是几种常见的方法:
1. 使用 open 和迭代器逐行读取
这是最常见的方法。通过文件对象的迭代器,逐行读取文件。
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 对每行进行处理
这种方式非常高效,因为它不会一次性将整个文件加载到内存,而是逐行读取。
2. 分块读取文件内容
如果需要以更大的块为单位读取,可以使用 read 方法指定块的大小。
with open('large_file.txt', 'r', encoding='utf-8') as file:
while True:
chunk = file.read(1024 * 1024) # 每次读取 1 MB
python requests 模块
requests 是 Python 中一个非常流行的用于发送 HTTP 请求的模块。它提供了一个简单易用的接口,可以用来发送各种类型的 HTTP 请求(如 GET、POST、PUT、DELETE 等),并处理响应数据。以下是 requests 模块的主要功能和常见用法:
安装 requests
如果尚未安装,可以使用以下命令安装:
pip install requests
1. 发送 GET 请求
1. requests.get函数是Python requests库中的一个方法,用于发送HTTP GET请求。其基本语法如下:
response = requests.get(url, params=None, **kwargs)
url:需要发送GET请求的URL地址。
params:可选参数,用于在URL中添加查询字符串参数,参数应以字典形式传递。
**kwargs:其他可选参数,如headers、timeout等,用于控制请求的其他方面。
2. requests.get函数的返回值内容
requests.get函数返回一个Response对象,该对象包含了服务器对请求的响应。Response对象包含以下常用属性和方法:
status_code:HTTP响应状态码(如200表示成功)。
text:响应内容的字符串表示,自动根据响应头中的字符编码进行解码。
content:响应内容的原始字节串,不会自动解码。
json():如果响应内容是JSON格式,该方法会将其解析为Python字典或列表。
headers:一个字典,包含服务器响应的所有头部信息。
python 如何通过subprocess.call调用自定义alias别名
为了更好的通过Python脚本执行linux命令,通过自定义别名(Alias)进行多个命令组合,然而通过python中如何通过subprocess类库
自定义alias
#alias lt='ls --human-readable --size -1 -S --classify'
alias lt='du -sh * | sort -h'
测试调用的Python代码
from subprocess import call
def test():
call("lt")
if __name__ == "__main__":
test()
直接运行上面的代码提示错误信息如下
Traceback (most recent call last):
File "test_alias.py", line 7, in <module>
test()
File "test_alias.py", line 4, in test
call("lt")
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'lt': 'lt'
通过错误信息可以看出lt命令被当作了文件或目录提示找不到
如果您需要的别名是在 ~/.bashrc 中定义的,可以通过尝试以下几种方式进行运行:
1)你必须给’shell’关键字:
subprocess.call('command', shell=True)
否则,您给定的命令用于查找可执行文件,而不是传递给 shell,它是扩展别名和函数等内容的 shell。
from subprocess import call
def test():
call("lt", shell=True)
if __name__ == "__main__":
test()
运行此处代码发现报错找不到文件或目录的错误了,但是出现了新的错误,错误信息如下
# /bin/sh: lt: command not found
有错误信息可以看出还是找不到lt命令,不过不报错误了(此处应该有掌声)
2) 默认情况下,subprocess.call 使用’/bin/sh’ shell。如果这是您要调用的 Bash 别名,则需要使用“可执行”关键字 告诉子进程使用 bash 而不是 sh:
subprocess.call('command', shell=True, executable='/bin/bash')
代码如下
from subprocess import call
def test():
call("lt", shell=True, executable='/bin/bash')
if __name__ == "__main__":
test()
通过执行代码发现,报错的错误同上,还是提示lt找到
3) 但是,/bin/bash 除非作为“交互式”shell(使用“-i”)启动,否则不会获取 ~/.bashrc。不幸的是,您不能传递 executable=’/bin/bash -i’,因为它认为整个值是可执行文件的名称。因此,如果您的别名是在用户的正常交互式启动中定义的,例如在 .bashrc 中,您必须使用以下替代形式调用命令:
subprocess.call(['/bin/bash', '-i', '-c', 命令])
# i.e. shell=False (the default)
from subprocess import call
def test():
call(['/bin/bash', '-i', '-c', 'lt'])
if __name__ == "__main__":
test()
正常执行,成功调用了alias命令
标签: python subprocess alias
python2 python3中long类型的区别
python2 python3中long类型的区别
python2中有long类型
python3中没有long类型,只有int类型
'python' engine because the 'c' engine does not support regex separators
moveielens.py:17: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.user = pd.read_table(path1, sep='::', header=None, names=unames)
pandas.read_table()函数,读取文件数据时,由于分隔符为'::',弹出如下警告
警告:ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)
解决方法:增加函数的引擎参数engine='python',如下:
user = pd.read_table(path1, sep='::', header=None, names=unames, engine='python')
标签: python pandas re read_table
importError c extension: No module named np_datetine not buit
我的python代码中有import pandas
使用pyinstaller进行打包exe的时候出现以下问题,现在就来说一下。
打包的时候没有报错,
但是执行时候首先报了pandas的错。提示没有找到pandas._lilbs.tslibs.np_datetime。大概的错误如下:
第一个错误是:
Fi1e sitepackagesp\pandas\init .py 1ine 35 in Kmodule?
importError c extension: No module named np_datetine not buit. Jf you yant to import pandas from. the source drectory
g you may need to run python setup. py buildext inplace force to bui1d the c extensions first:
iFai1ed to execute script smg
通过网上查找的方法,修改下pyinstaller的用法,生成过程中添加--hiddenimport=pandas._libs.tslibs.np_datetime,代码如下
pyinstaller -F -w smg.py --hiddenimport=pandas._libs.tslibs.np_datetime
继续打包,过程中没有报错,继续执行exe文件的时候报错如下
第二个错误:
Fi1e sitepackagesp\pandas\init .py 1ine 35 in Kmodule?
Fi1e sitepackagesp\pandas\init .py 1ine 35 in Kmodule?
importError c extension: No module named timedeltas not buit. Jf you yant to import pandas from. the source drectory
g you may need to run python setup. py buildext inplace force to bui1d the c extensions first:
iFai1ed to execute script smg
iFai1ed to execute script smg标签: pandas np_datetime timedeltas
RuntimeError: Python is not installed as a framework
今天在mac上,python virtualenv 虚拟环境下运行matplotlib example的时候提示如下报错:python animation/animated_histogram.py
Traceback (most recent call last):
File "animation/animated_histogram.py", line 11, in <module>
import matplotlib.pyplot as plt
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup
[backend_name], 0)
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/backend_macosx.py", line 17, in <module>
from matplotlib.backends import _macosx
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
标签: python matplotlib RuntimeError
error: command 'gcc' failed with exit status 1
错误:error: command 'gcc' failed with exit status 1在 centons 使用pip安装Python模块出现error: command 'gcc' failed with exit status 1 ,明明装了gcc的,怎么会不行呢,然后发觉是failed不是not found,这说明这个错误个gcc没多大关系,应该是缺少某些功能模块,然后谷歌了一下,先后安装了python-devel,libffi-devel后还是不行,最后发觉要安装openssl-devel才行
可如下命令行安装:
yum install gcc libffi-devel python-devel openssl-devel
Python四种逐行读取文件内容的方法
下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。方法一:readline函数
#-*- coding: UTF-8 -*-
f = open("./code.txt") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
#print line, # 在 Python 2中,后面跟 ',' 将忽略换行符
print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
优点:节省内存,不需要一次性把文件内容放入内存中
缺点:速度相对较慢
标签: python open fileinput readline readlines
Python 快速实现 FTP 服务器
有时当你想快速搭建一个 FTP 服务器来临时实现文件上传下载时,这是特别有用的。我们这里利用 Python 的 Pyftpdlib 模块可以快速的实现一个 FTP 服务器的功能。首先安装 Pyftpdlib 模块
$ sudo pip install pyftpdlib
The directory '/Users/xiaodu/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/xiaodu/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pyftpdlib
Installing collected packages: pyftpdlib
Successfully installed pyftpdlib-1.5.3
热门日志
分类
- Django(4)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(32)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- shell(3)
- about(1)
- git(9)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(2)
- 架构(18)
- Vue(1)
- game(2)
- Html(6)
- Java(8)
- Mysql(37)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(72)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(48)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(12)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)