`

python file

 
阅读更多

 

打开文件file_handler = open(filename,mode)

open(filename[, mode[, bufsize]])

Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

The first two arguments are the same as for stdio‘s fopen: filename is the file name to be opened, and mode is a string indicating how the file is to be opened.

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

In addition to the standard fopen values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

Python enforces that the mode, after stripping 'U', begins with 'r', 'w' or 'a'.

Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.

Changed in version 2.5: Restriction on first letter of mode string introduced.

 

    mode:
    r 只读
    w 写,覆盖已有内容。
    a 追加模式,如果文件不存在则创建
    r+ 读写
    w+ 消除文件内容,然后以读写方式打开文件。
    a+ 读写方式,并把文件指针移到文件尾。
    b 二进制模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。
    读取文件内容

File Objects

        File objects are implemented using C’s stdio package and can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

        When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.

 
    f.read([count]) 读出文件,如果有count,则读出count个字节。Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.


    f.readline() 读出一行信息。


    f.readlines()读出所有行,也就是读出整个文件的信息。写入文件内容


    f.write(string)把string字符串写入文件。


    f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

    换行符在各个操作系统中界定的不同,Windows换行符是‘\r\n',Unix/Linux的换行符为'\n',Mac的换行符为'\r';
    在python中,对换行符进行了统一处理,定义为'\n',以文本模式写入时,如果是Windows系统,则python会自动将\n转为\r\n,Mac系统类似


文件指针操作
    f.seek(offset[,where]) 把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。


    f.tell()获得文件指针位置。


文件信息操作
    f.fileno()获得文件描述符,是一个数字. Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntl module or os.read() and friends.
    f.isatty()如果文件是一个交互终端,则返回True,否则返回False。

 

其他
    f.close()
    f.flush(): Flush the internal buffer, like stdio‘s fflush. This may be a no-op on some file-like objects.
    f.truncate([size]) 截取文件,使文件的大小为size。

举例:
    打印当前文件目录 data文件夹下的所有文件

import os
procPath=os.getcwd()
dataPath=procPath+"/data"
files=[files for files in os.listdir(dataPath) ]  #if (files.find(timestamp) != -1)]
print files

 

    基本读写

#!/usr/bin/env python
# -*- coding: gb18030 -*-

poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''

#1. write file
f=open('poem.txt', 'w') #open for 'w'riting
f.write(poem) #write text to file
f.close() #close the file

#2. read file
f=open('poem.txt') #if no mode is specified, 'r'ead mode is assumed by default

while True:
    line=f.readline()
    if len(line) == 0: #Zero length indicates EOF
        #此时line==""
        break
    print line, #notice comma to avoid automatic newline

f.close() #close the file

#3. append file
f=open('poem.txt','a')
f.write('hehe')
f.write("haha")
f.close()

    

    按行读写

#!/usr/bin/env python
# -*- coding: gb18030 -*-

'''
本文件说明:

    1. “list”遍历
        for ind in range(0,len(sample_list), 1):
            sample_list[ind]    #这样可以得到下标
            ...
        或
        for ele in sample_list
            ele	                #这样也行,但不能得到下标
            ...
        
    2. “Python类型判断”:  type(ele) is types.IntType 和 type(ele) == types.StringType是等价的——
        (1) type的返回值是一个"类",types.IntType也是一个"类"
        (2) is 比较的是是否指向同一个对象; == 比较的是类型的值

    3. “Python类型转换”:
         int(x [,base ])         将x转换为一个整数
         long(x [,base ])        将x转换为一个长整数
         float(x )               将x转换到一个浮点数
         complex(real [,imag ])  创建一个复数
         str(x )                 将对象 x 转换为字符串 ; 转为字符串也可以类似这样做 "%d" %int_var
         repr(x )                将对象 x 转换为表达式字符串
         eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象
         tuple(s )               将序列 s 转换为一个元组
         list(s )                将序列 s 转换为一个列表
         chr(x )                 将一个整数转换为一个字符
         unichr(x )              将一个整数转换为Unicode字符
         ord(x )                 将一个字符转换为它的整数值
         hex(x )                 将一个整数转换为一个十六进制字符串
         oct(x )                 将一个整数转换为一个八进制字符串
         
    4. 字符串变量 和 字符串常量 不同:
        字符串变量 在“拼接”时,需要加上“+”   i.e. str_var+"hehe"
        字符串常量 在“拼接”时,直接拼接      i.e. "sam""hehe"
        
    5. 按行写入文件
'''

import types

sample_list=['hehe',"Haha",3,"哈哈","Hey\\Hey","三木!"]
for ind in range(0,len(sample_list),1):
    if type(sample_list[ind]) is types.IntType:     #类型判断
        #sample_list[ind]=("%d\n" %sample_list[ind]) #int变量转字符串需要这样: "%d" %i
        sample_list[ind]=str(sample_list[ind])+"\n"  #字符串变量+字符串常量
    elif type(sample_list[ind]) is types.StringType:
        sample_list[ind]=(sample_list[ind]+"\n")    #字符串变量+字符串常量
    else:
        pass

#观察打印出list和list[i]的区别,体会print的功能
print
print sample_list
print sample_list[3]

#按行写入文件
f=open('myFile.txt','a')
f.writelines(sample_list)  #writelines(list)是不会自动加上换行符的
f.close()

    

 

 

 

 

 

分享到:
评论

相关推荐

    node-v12.14.0-darwin-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    基于使用microPython的开发单片机设计源码.zip

    我们在单片机开发中常会遇到需要将UTF-8转换为GBK编码的需求。在了解各种编码格式的情况下可知, UFT-8不能直接转成GBK,需中转成unicode再转换为gbk。而unicode和gbk之间没有算法可以直接计算,需要查表方式获取。 网上有一些C语言实现的代码,我这里分享一种microPython的实现代码 接下来就是要考虑表的存储方式了,刚开始我想着把表存到代码里直接通过索引实现编码转换。但是gb2312有七千多个字符全部存储要耗费很大内存,即使是32位的esp32也只有512k的内存,加上其他资源的消耗,剩余的内存不足以存储编码转换表。 于是只能将表保存成一个文件(转化成bin文件会比较好,方法类似),通过读写文件来减少内存开销。 具体的查表就是简单的二分法

    基于VB实现的车队综合业务管理系统(论文+源代码)

    基于VB实现的车队综合业务管理系统(论文+源代码) 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。

    基于知识图谱的推荐算法-NCFG的实现python源码+运行说明.zip

    基于知识图谱的推荐算法-NCFG的实现 运行环境 python == 3.7.0 torch == 1.12.0 pandas == 1.1.5 numpy == 1.21.6 sklearn == 0.0 数据集介绍 music-音乐 book-书籍 ml-电影 yelp-商户 文件介绍 ratings.txt:记录用户点击的项目,1代表点击了,0代表没有点击 kg.txt:知识图谱文件,第一列是头实体,第二列是尾实体,第三列是关系 user-list.txt:用户及其id文件,第一列是用户的id,第二列是用户 其余文件可忽略

    JAVA002打飞机游戏设计(程序+设计说明书).zip

    JAVA002打飞机游戏设计(程序+设计说明书).zip

    Engineering-Electromagnetic-Theory-Lab-3.pdf

    Engineering_Electromagnetic_Theory_Lab_3.pdf

    自己弄的基于matlab实现的多端直流配电网的仿真模型,是支撑自己小论文的东东 仿真环境是用的matlab

    自己弄的基于matlab实现的多端直流配电网的仿真模型,是支撑自己小论文的东东。仿真环境是用的matlab。

    BBR、A2O、MBR工艺比选.doc

    课程设计,污水处理设计方案

    DHT11温湿度传感器是一款高性能、低成本的数字温湿度复合传感器 它集成了温度感应和湿度感应功能,可以准确地测量环境中的温度和湿

    DHT11温湿度传感器是一款高性能、低成本的数字温湿度复合传感器。它集成了温度感应和湿度感应功能,可以准确地测量环境中的温度和湿度,并通过数字信号输出数据。以下是关于DHT11温湿度传感器的详细介绍: DHT11传感器内部包含一个NTC热敏电阻用于温度测量和一个薄膜电容湿度传感材料用于湿度测量。NTC热敏电阻的电阻值会随着温度的变化而变化,DHT11通过测量电阻值的变化来计算环境的温度。而薄膜电容湿度传感材料的电容值则会随着湿度的变化而变化,DHT11通过测量电容值的变化来计算环境的湿度。 DHT11传感器具有高精度、高可靠性和稳定性好的特点。其湿度测量范围为20%RH至90%RH,精度可达±5%RH;温度测量范围为-20℃至+60℃,精度可达±2℃。传感器的工作电压范围为3.3V至5.5V,工作电流较小,功耗低。此外,DHT11传感器还具有超长的信号传输距离和超强的抗干扰能力,可以在复杂的环境中稳定工作。 DHT11传感器采用单总线数字信号传输方式,通过单个引脚进行数据输入和输出。它使用特定的时序信号来传输温度和湿度数据,主机可以通过解析这些时序信号来获取温度和湿度的数值。这种

    某钢厂转炉浊环供水泵站给排水竣工图.zip

    污水处理

    delphi家庭财务管理系统.zip

    delphi家庭财务管理系统.zip

    node-v10.23.2-linux-arm64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    ASP+ACCESS网上人才信息管理系统(源代码+设计说明书).zip

    ASP+ACCESS网上人才信息管理系统(源代码+设计说明书).zip

    ASP基于BS结构的工厂设备管理系统的设计与开发(源代码+设计说明书).zip

    ASP基于BS结构的工厂设备管理系统的设计与开发(源代码+设计说明书).zip

    node-v10.23.3-linux-arm64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    埃森哲_组织设计的指导思想gl.ppt

    埃森哲_组织设计的指导思想gl.ppt

    卷积神经网络(Convolutional Neural Networks,CNN)是深度学习领域中一种非常重要的神经网络结构,特

    卷积神经网络(Convolutional Neural Networks,CNN)是深度学习领域中一种非常重要的神经网络结构,特别适用于处理图像和视频数据。以下是关于卷积神经网络的500字资源介绍: 卷积神经网络是一类包含卷积计算的前馈神经网络,它的核心在于“卷积与池化”操作。在卷积层中,神经元仅与部分邻层神经元连接,这种局部连接和权值共享的特性使得卷积神经网络能够以较小的计算量学习格点化特征,如像素和音频,且稳定有效。 卷积神经网络的主要构成包括卷积层、池化层和全连接层。卷积层通过卷积核对输入图像进行特征提取,生成特征图;池化层则对特征图进行下采样,降低数据维度,同时保留重要信息;全连接层则负责将提取的特征进行整合,用于分类或回归任务。 卷积神经网络在计算机视觉领域具有广泛的应用,如图像分类、目标检测、人脸识别等。通过训练大量的图像数据,卷积神经网络能够自动学习图像的特征表示,比传统的手工设计特征方法更加有效。此外,卷积神经网络也被应用于自然语言处理、语音识别等领域,并取得了显著的成果。 总之,卷积神经网络是一种强大的深度学习模型,它通过模拟人类的视觉系统来处理图像和视频数据

    基于VB+access实现的小区物业管理系统(系统+论文).zip

    基于VB+access实现的小区物业管理系统(系统+论文) 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。

    基于matlab实现的用于边角网平差,可实现平差、误差椭圆绘制、成果坐标输出等 内附参考观测数据.rar

    基于matlab实现的用于边角网平差,可实现平差、误差椭圆绘制、成果坐标输出等 内附参考观测数据.rar

    ASP+ACCESS新闻发布系统(源代码+设计说明书).zip

    ASP+ACCESS新闻发布系统(源代码+设计说明书).zip

Global site tag (gtag.js) - Google Analytics