Python文件读取的3种方法及路径转义

| 收藏本文 下载本文 作者:岳麓飞剑

下面是小编帮大家整理的Python文件读取的3种方法及路径转义(共含7篇),希望对大家带来帮助,欢迎大家分享。同时,但愿您也能像本文投稿人“岳麓飞剑”一样,积极向本站投稿分享好文章。

Python文件读取的3种方法及路径转义

篇1:Python文件读取的3种方法及路径转义

这篇文章主要介绍了Python文件读取的3种方法及路径转义,本文分别给出读取文件的代码实例,最后讲解了路径转义的相关知识、小技巧,需要的朋友可以参考下

1.文件的读取和显示

方法1:

代码如下:

f=open(r‘G:\2.txt‘)

print f.read

f.close()

方法2:

代码如下:

try:

t=open(r‘G:\2.txt‘)

print t.read()

finally:

if t:

t.close()

方法3:

代码如下:

with open(r‘g:\2.txt‘) as g:

for line in g:

print line

python虽然每次打开文件都要关闭,但是可能会由于异常导致未关闭,因此我们最好是手动关闭,方法二通过异常处理来进行,方法三通过with来自动调用close方法,最简便,

这里open的地址需要注意,如果我们写成open(‘g:\2.txt‘,‘r‘)运行时会报错:IOError: [Errno 22] invalid mode (‘r‘) or filename: ‘g:\x02.txt‘,

这里是由于路径被转义了,因此可以用‘/‘代替‘\‘:f=open(‘g:/2.txt‘,‘r‘)或者加上r‘path‘:f=open(r‘g:\2.txt‘,‘r‘)就可以了。

这里通过python自带的ide-GUI测试一下是怎样转义的:

代码如下:

Python 2.7.6 (default, Nov 10 , 19:24:18) [MSC v.1500 32 bit (Intel)] on win32

Type “copyright”, “credits” or “license()” for more information.

>>>f=‘g:\a.txt‘

>>>print f

g:.txt #这里被转义成一个特殊符号了。

>>>f1=‘g:\\a.txt‘

>>>print f1

g:\a.txt #没被转义

>>>r‘g:\a.txt‘

‘g:\\a.txt‘ #没被转义

>>>‘g:\a.txt‘

‘g:\x07.txt‘ #这里将a转义

>>>‘g:\\a.txt‘

‘g:\\a.txt‘

>>>

篇2:python读取浮点数和读取文件示例

2013-04-04Python编写的com组件发生R6034错误的原因与解决办法

2013-04-0450行代码实现贪吃蛇(具体思路及代码)

2013-11-11使用python BeautifulSoup库抓取58手机维修信息

-02-02python访问sqlserver示例

2014-02-02python和pyqt实现360的CLable控件

2013-12-12python调用cmd复制文件代码分享

2013-02-02python中的一些类型转换函数小结

-03-03学习python处理python编码问题

-04-04python启动办公软件进程(word、excel、ppt、以及wps的et、wps、w

2013-03-03python赋值操作方法分享

篇3:python读取浮点数和读取文件示例

最近更 新

python监控网卡流量并使用graphite绘图的

Python使用Socket(Https)Post登录百度的实

Eclipse + Python 的安装与配置流程

python抓取网页图片示例(python爬虫)

简单的通用表达式求10乘阶示例

python2.7删除文件夹和删除文件代码实例

Python 变量类型及命名规则介绍

Python下的Mysql模块MySQLdb安装详解

python从ftp下载数据保存实例

python算法学习之计数排序实例

热 点 排 行

Python入门教程 超详细1小时学会

python 中文乱码问题深入分析

比较详细Python正则表达式操作指

Python字符串的encode与decode研

Python open读写文件实现脚本

Python enumerate遍历数组示例应

Python 深入理解yield

Python+Django在windows下的开发

python 文件和路径操作函数小结

python 字符串split的用法分享

篇4:Shell逐行读取文件的4种方法

这篇文章主要介绍了Shell逐行读取文件的4种方法,本文介绍了while循环法、重定向法、管道法、文件描述符法等一些方法,需要的朋友可以参考下

在Linux中有很多方法逐行读取一个文件的方法,其中最常用的就是下面的脚本里的方法,而且是效率最高,使用最多的方法,为了给大家一个直观的感受,我们将通过生成一个大的文件的方式来检验各种方法的执行效率。

方法1:while循环中执行效率最高,最常用的方法。

代码如下:

function while_read_LINE_bottm{

While read LINE

do

echo $LINE

done < $FILENAME

}

注释:我习惯把这种方式叫做read釜底抽薪,因为这种方式在结束的时候需要执行文件,就好像是执行完的时候再把文件读进去一样。

方法2 : 重定向法;管道法: cat $FILENAME | while read LINE

代码如下:

Function While_read_LINE(){

cat $FILENAME | while read LINE

do

echo $LINE

done

}

注释:我只所有把这种方式叫做管道法,相比大家应该可以看出来了吧。当遇见管道的时候管道左边的命令的输出会作为管道右边命令的输入然后被输入出来。

方法3: 文件描述符法

代码如下:

Function while_read_line_fd(){

Exec 3<&0

Exec 0<$FILENAME

While read LINE

Do

Echo $LINE

Exec 0<&<3

}

注释: 这种方法分2步骤,第一,通过将所有内容重定向到文件描述符3来关闭文件描述符0.为此我们用了语法Exec 3<&0 。第二部将输入文件放送到文件描述符0,即标准输入。

方法4   for 循环。

代码如下:

function for_in_file(){

For i in `cat $FILENAME`

do

echo $i

done

}

注释:这种方式是通过for循环的方式来读取文件的内容相比大家很熟悉了,这里不多说。对各个方法进行测试,看那方法的执行效率最高。

首先我们用脚本(脚本见附件)生成一个70000行的文件,文件位置在/scripts/bigfile。然后通过下面的脚本来测试各个方法的执行效率,脚本很简单,不再解释。

代码如下:

#!/bin/bash

FILENAME=“$1”

TIMEFILE=“/tmp/loopfile.out” >$TIMEFILE

SCRIPT=$(basename $0)

function usage(){

echo -e “\nUSAGE: $SCRIPT. file \n”

exit 1

}

function while_read_bottm(){

while read LINE

do

echo $LINE

done < $FILENAME

}

function while_read_line(){

cat $FILENAME | while read LINE

do

echo $LINE

done

}

function while_read_line_fd(){

exec 3<&0

exec 0< $FILENAME

while read LINE

do

echo $LINE

done

exec 0<&3

}

function for_in_file(){

for i in `cat $FILENAME`

do

echo $i

done

}

if [ $# -lt 1 ] ; then

usage

fi

echo -e “ \n starting file processing of each method\n”

echo -e “method 1:”

echo -e “function while_read_bottm”

time while_read_bottm >>$TIMEFILE

echo -e “\n”

echo -e “method 2:”

echo -e “function while_read_line ”

time while_read_line >>$TIMEFILE

echo -e “\n”

echo -e “method 3:”

echo “function while_read_line_fd”

time while_read_line_fd >>$TIMEFILE

echo -e “\n”

echo -e “method 4:”

echo -e “function for_in_file”

time for_in_file >>$TIMEFILE

执行脚本后: [root@localhost shell]# ./while /scripts/bigfile

脚本输出内容:

代码如下:

method 1:

function while_read_bottm

real   0m5.689s

user   0m3.399s

sys   0m1.588s

method 2:

function while_read_line

real   0m11.612s

user   0m4.031s

sys   0m4.956s

method 3:

function while_read_line_fd

real   0m5.853s

user   0m3.536s

sys   0m1.469s

method 4:

function for_in_file

real   0m5.153s

user   0m3.335s

sys   0m1.593s

下面我们对各个方法按照速度进行排序,

代码如下:

real   0m5.153s   method 4 (for 循环法)

real   0m5.689s   method 1 (while 釜底抽薪法)

real   0m5.853s   method 3   (标识符法)

real   0m11.612s method 2   (管道法)

由此可见在各个方法中,for语句效率最高,而在while循环中读写文件时,

代码如下:

while read LINE

do

echo $LINE

done < $FILENAME

方式执行效率最高。

篇5:Python合并字符串的3种方法

这篇文章主要介绍了Python合并字符串的3种方法,本文讲解了使用+=操作符、使用%操作符、使用String的‘ ‘.join()方法3种方法,需要的朋友可以参考下

目的

将一些小的字符串合并成一个大字符串,更多考虑的是性能

方法

常见的方法有以下几种:

1.使用+=操作符

代码如下:

BigString=small1+small2+small3+...+smalln

例如有一个片段pieces=[‘Today‘,‘is‘,‘really‘,‘a‘,‘good‘,‘day‘],我们希望把它联起来

代码如下:

BigString=‘ ‘

for e in pieces:

BigString+=e+‘ ‘

或者用

代码如下:

import operator

BigString=reduce(operator.add,pieces,‘ ‘)

2.使用%操作符

代码如下:

In [33]: print ‘%s,Your current money is %.1f‘%(‘Nupta‘,500.52)

Nupta,Your current money is 500.5

3.使用String的‘ ‘.join()方法

代码如下:

In [34]: ‘ ‘.join(pieces)

Out[34]: ‘Today is really a good day‘

关于性能

有少量字符串需要拼接,尽量使用%操作符保持代码的可读性

有大量字符串需要拼接,使用‘‘.join方法,它只使用了一个pieces的拷贝,而无须产生子项之间的中间结果,

Python合并字符串的3种方法

篇6:Python安装第三方库的3种方法

这篇文章主要介绍了Python安装第三方库的3种方法,本文讲解了通过setuptools来安装python模块、通过pip来安装python模块、直接从网上下载下可执行文件来安装三种方法,需要的朋友可以参考下

【方法一】: 通过setuptools来安装python模块

首先下载 peak.telecommunity.com/dist/ez_setup.py

NOTE: 最好下载个setuptools,本人是15.2版本,里面包含了ez_setup

运行 python ez_setup.py

D:\work\installation\setuptools-15.2\setuptools-15.2>python ez_setup.py >1.txt Extracting in c:\users\admini~1\appdata\local\temp\tmpbxikxf Now working in c:\users\admini~1\appdata\local\temp\tmpbxikxf\setuptools-15.2 Installing Setuptools ...... Copying setuptools-15.2-py2.7.egg to c:\python27\lib\site-packages setuptools 15.2 is already the active version in easy-install.pth Installing easy_install-script.py script. to C:\Python27\Scripts Installing easy_install.exe script. to C:\Python27\Scripts Installing easy_install-2.7-script.py script. to C:\Python27\Scripts Installing easy_install-2.7.exe script. to C:\Python27\Scripts Installed c:\python27\lib\site-packages\setuptools-15.2-py2.7.egg Processing dependencies for setuptools==15.2 Finished processing dependencies for setuptools==15.2

运行 easy_install py

D:\work>easy_install py#py 为第三方库文件 Searching for py Best match: py 1.4.26 Adding py 1.4.26 to easy-install.pth file Using c:\python27\lib\site-packages Processing dependencies for py Finished processing dependencies for py

【方法二】: 通过pip来安装python模块

安装 easy_install pip

D:\work>easy_install pip Searching for pip Best match: pip 6.1.1 Processing pip-6.1.1-py2.7.egg pip 6.1.1 is already the active version in easy-install.pth Installing pip-script.py script. to C:\Python27\Scripts Installing pip.exe script. to C:\Python27\Scripts Installing pip2.7-script.py script. to C:\Python27\Scripts Installing pip2.7.exe script. to C:\Python27\Scripts Installing pip2-script.py script. to C:\Python27\Scripts Installing pip2.exe script. to C:\Python27\Scripts Using c:\python27\lib\site-packages\pip-6.1.1-py2.7.egg Processing dependencies for pip Finished processing dependencies for pip

运行 pip install xlrd

Usage: pip [options] Commands: install Install packages. uninstall Uninstall packages. freeze Output installed packages in requirements format. listList installed packages. showShow information about installed packages. search Search PyPI for packages. wheelBuild wheels from your requirements. zip DEPRECATED. Zip individual packages. unzipDEPRECATED. Unzip individual packages. helpShow help for commands. General Options: -h, --help Show help. --isolated Run pip in an isolated mode, ignoring environment variables and user configuration. -v, --verbose Give more output. Option is additive, and can be used up to 3 times. -V, --version Show version and exit. -q, --quiet Give less output. --log

Path to a verbose appending log. --proxy

Specify a proxy in the form. [user:passwd@]proxy.server:port. --retries Maximum number of retries each connection should attempt (default 5 times). --timeout Set the socket timeout (default 15 seconds). --exists-action Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. --trusted-host Mark this host as trusted, even though it does not have valid or any HTTPS. --cert

Path to alternate CA bundle. --client-cert

Path to SSL client certificate, a single file containing the private key and the certificate in PEM format. --cache-dir

Store the cache data in . --no-cache-dir Disable the cache. --disable-pip-version-check Don‘t periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.

【方法三】:直接从网上下载下可执行文件来安装.

比如说,去 >>>pythonlibs <<< 网站,提供了很多Python非官方包下载,二进制文件,下载安装方便.

篇7:Python常用的文件及文件路径、目录操作方法介绍

这篇文章主要介绍了Python常用的文件及文件路径、目录操作方法汇总介绍,本文集合了最常用的一些文件和目录操作函数,并一一介绍它们的作用,需要的朋友可以参考下

python的文件和路径操作函数基本上位于os和os.path模块中,

os.listdir(dirname):列出dirname下的目录和文件

os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false

os.path.isfile(name):判断name是不是一个文件,不存在name也返回false

os.getcwd():获得当前工作目录

os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录

作为文件名而分离,同时它不会判断文件或目录是否存在)

os.path.splitext():分离文件名与扩展名

os.path.basename(path):返回文件名

os.path.dirname(path):返回文件路径

os.path.join(path,name):连接目录与文件名或目录

可以使用简单的方法匹配某个目录下的所有子目录或文件,用法也很简单。 glob.glob(regression) 返回一个列表

os.listdir(dirname)

功能相当于在dirname目录下执行dir命令,它返回一个list。不包括dirname的文件和目录的list

代码如下:

>>>os.listdir(“d:/github”)

[‘about.html‘, ‘book‘, ‘en‘, ‘feiyuliu.github.com‘, ‘life‘, ‘pyssh‘, ‘PythonStud

y‘, ‘StudyShell‘]

其中about.html是文件,feiyuliu.github.com是目录,

os.path.split(path)

path为一个路径,返回一个元组,把path分为两部分。

代码如下:

>>>os.path.split(“d:/github/about.html”)

(‘d:/github‘, ‘about.html‘)

>>>os.path.split(“about.html”)

(‘‘, ‘about.html‘)

os.path.splitext(filename)

把文件分为文件名称路径和扩展名。返回一个元组。

代码如下:

>>>os.path.splitext(“about.html”)

(‘about‘, ‘.html‘)

>>>os.path.splitext(“d:/github/about.html”)

(‘d:/github/about‘, ‘.html‘)

os.path.dirname(path)

把目录输出,不输出文件名。返回字符串类型。

代码如下:

>>>os.path.dirname(“d:/github/about.html”)

‘d:/github‘

>>>os.path.dirname(“about.html”)

‘‘ #输出为空

os.path.basename(filename)

取得文件名。返回字符串类型

代码如下:

>>>os.path.basename(“d:/github/about.html”)

‘about.html‘ #注意不包括目录

shell下同时读取多个文件的方法

RC4文件加密的python实现方法

用python分割TXT文件成4K的TXT文件

Python构造函数及解构函数介绍

Python删除指定目录下过期文件的2个脚本

公司文件管理制度及流程

文件词语解释及造句

学好语文的五种方法及技巧

Python的Bottle框架中返回静态文件和JSON对象的方法

python文件读写操作与linux shell变量命令交互执行的方法

Python文件读取的3种方法及路径转义(通用7篇)

欢迎下载DOC格式的Python文件读取的3种方法及路径转义,但愿能给您带来参考作用!
推荐度: 推荐 推荐 推荐 推荐 推荐
点击下载文档 文档为doc格式

热门推荐

HOT

猜你喜欢

NEW
点击下载本文文档