file的一些读写操作

The easiest way to create a text stream is with open(), optionally specifying an encoding:

f = open("myfile.txt", "r", encoding="utf-8")

In-memory text streams are also available as StringIO objects:

f = io.StringIO("some initial text data")

The text stream API is described in detail in the documentation of TextIOBase.

>>> file= open('testfile', 'r')
>>> help(file.read)

1. read(size=-1, /) method of _io.TextIOWrapper instance
    Read at most n characters from stream.
    
    Read from underlying buffer until we have n characters or we hit EOF.
    If n is negative or omitted, read until EOF.
(END)
 

read(size=-1)

Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

>>> file.read()
'sf\nfdgret\nytuytuyt\n324\n'

>>>file.close()

>>> file= open('testfile', 'r')
>>> type(file.read())
<class 'str'>
>>> 

>>> file.read()
'sf\nfdgret\nytuytuyt\n324\n'
>>> 
 

2. readline(size=-1)

Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned.

If size is specified, at most size characters will be read.

3. readlines(hint=-1, /) method of _io.TextIOWrapper instance
    Return a list of lines from the stream.
    
    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.
(END)

>>> file= open('testfile', 'r')

>>> file.readlines()
['sf\n', 'fdgret\n', 'ytuytuyt\n', '324\n']
 


 

写:

1. truncate(size=None)

Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.

Changed in version 3.5: Windows will now zero-fill files when extending.

2. writable()

Return True if the stream supports writing. If Falsewrite() and truncate() will raise OSError.

3. writelines(lines)

Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

4. write(text, /) method of _io.TextIOWrapper instance
    Write string to stream.
    Returns the number of characters written (which is always equal to
    the length of the string).

with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')


 

5. replace(...)
    S.replace(old, new[, count]) -> str
    
    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
(END)
 


import re
 
fp3=open("file3.txt","r")
fp4=open("file4.txt","w")
 
for s in fp3.readlines():#先读出来   
    fp4.write(s.replace("hello","goood")) #替换 并写入
    
fp3.close()
fp4.close()

file4.txt可以是个空文件
[allen@oc1623636125 ~]$ cat file3.txt
hello,
sdfsdgerthello
sdfsdfsdg
sfsdfsdf
hellosdfsdf

[allen@oc1623636125 ~]$ cat test.py
import re
 
fp3=open("file3.txt","r")
fp4=open("file4.txt","w")
 
for s in fp3.readlines():#先读出来   
    fp4.write(s.replace("hello","goood")) #替换 并写入
    
fp3.close()
fp4.close()
[allen@oc1623636125 ~]$ python3 test.py


[allen@oc1623636125 ~]$ cat file4.txt
goood,
sdfsdgertgoood
sdfsdfsdg
sfsdfsdf
gooodsdfsdf
[allen@oc1623636125 ~]$ 

python进行文件读写的函数是open或file


file_handler = open(filename,,mode)
Table mode

file(name[, mode[, buffering]]) 
file()函数用于创建一个file对象,它有一个别名叫open(),可能更形象一些,它们是内置函数。来看看它的参数。它参数都是以字符串的形式传递的。name是文件的名字。
mode是打开的模式,可选的值为r w a U,分别代表读(默认) 写 添加支持各种换行符的模式。用w或a模式打开文件的话,如果文件不存在,那么就自动创建。此外,用w模式打开一个已经存在的文件时,原有文件的内容会被清空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉。由于历史的原因,换行符在不同的系统中有不同模式,比如在 unix中是一个\n,而在windows中是‘\r\n’,用U模式打开文件,就是支持所有的换行模式,也就说‘\r’ '\n' '\r\n'都可表示换行,会有一个tuple用来存贮这个文件中用到过的换行符。不过,虽说换行有多种模式,读到python中统一用\n代替。在模式字符的后面,还可以加上+ b t这两种标识,分别表示可以对文件同时进行读写操作和用二进制模式、文本模式(默认)打开文件。
buffering如果为0表示不进行缓冲;如果为1表示进行“行缓冲“;如果是一个大于1的数表示缓冲区的大小,应该是以字节为单位的。

file对象有自己的属性和方法。先来看看file的属性。


closed #标记文件是否已经关闭,由close()改写 
encoding #文件编码 
mode #打开模式 
name #文件名 
newlines #文件中用到的换行模式,是一个tuple 
softspace #boolean型,一般为0,据说用于print

file的读写方法:


F.read([size]) #size为读取的长度,以byte为单位 
F.readline([size]) 
#读一行,如果定义了size,有可能返回的只是一行的一部分 
F.readlines([size]) 
#把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。 
F.write(str) 
#把str写到文件中,write()并不会在str后加上一个换行符 
F.writelines(seq) 
#把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西。 
file的其他方法:


F.close() 
#关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError 
F.flush() 
#把缓冲区的内容写入硬盘 
F.fileno() 
#返回一个长整型的”文件标签“ 
F.isatty() 
#文件是否是一个终端设备文件(unix系统中的) 
F.tell() 
#返回文件操作标记的当前位置,以文件的开头为原点 
F.next() 
#返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。 
F.seek(offset[,whence]) 
#将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。 
F.truncate([size]) 
#把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

发布了36 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39833509/article/details/103780751