python循环读取文件内容(python如何循环读取文件)

http://www.itjxue.com  2023-04-09 01:15  来源:未知  点击次数: 

python如何读取文件的内容

# _*_ coding: utf-8 _*_

import pandas as pd

# 获取文件的内容

def get_contends(path):

with open(path) as file_object:

contends = file_object.read()

return contends

# 将一行内容变成数组

def get_contends_arr(contends):

contends_arr_new = []

contends_arr = str(contends).split(']')

for i in range(len(contends_arr)):

if (contends_arr[i].__contains__('[')):

index = contends_arr[i].rfind('[')

temp_str = contends_arr[i][index + 1:]

if temp_str.__contains__('"'):

contends_arr_new.append(temp_str.replace('"', ''))

# print(index)

# print(contends_arr[i])

return contends_arr_new

if __name__ == '__main__':

path = 'event.txt'

contends = get_contends(path)

contends_arr = get_contends_arr(contends)

contents = []

for content in contends_arr:

contents.append(content.split(','))

df = pd.DataFrame(contents, columns=['shelf_code', 'robotid', 'event', 'time'])

扩展资料:

python控制语句

1、if语句,当条件成立时运行语句块。经常与else, elif(相当于else if) 配合使用。

2、for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。

3、while语句,当条件为真时,循环运行语句块。

4、try语句,与except,finally配合使用处理在程序运行中出现的异常情况。

5、class语句,用于定义类型。

6、def语句,用于定义函数和类型的方法。

用python读取文本文件,对读出的每一行进行操作,这个怎么写?

用python读取文本文件,对读出的每一行进行操作,写法如下:

f?=?open("test.txt",?"r")

while?True:

line?=?f.readline()

if?line:

pass????#?do?something?here

line=line.strip()

p=line.rfind('.')

filename=line[0:p]

print?"create?%s"%line

else:

break

f.close()

扩展资料:

Python将txt文件读取到一个字符串里的操作方法如下:

1、首先,添加Python文件和文本文件以在vscode中读取,如下图所示。

2、其次,完成上述步骤后,在txt文件中写入一些内容以用于内容读取,只需将其写入即可,如下图所示。

3、接着,完成上述步骤后,必须导入os文件,以便可以在os中调用某些文件操作方法,如下图所示。

4、然后,完成上述步骤后,打开要读取的文件,并将读取的内容数据复制到字符串中,如下图所示。

5、随后,完成上述步骤后,打印字符串以显示内容,以方便参考,如下图所示。

6、接着,完成上述步骤后,运行jy.py文件,该文件将开始读取和打印内容,如下图所示。

7、最后,完成上述步骤后,可以看到已读取txt文件的内容,如下图所示。

python如何实现for循环操作文件?

python用for循环遍历文件操作,代码如下:

#!\urs\bin\env?python

#encoding:utf-8???????#设置编码方式??

import?os

import?re

class?loop_file:

????def?__init__(self,?root_dir,?short_exclude=[],?long_exclude=[],?file_extend=[]):

????????self.root_dir?=?root_dir

????????self.short_exclude?=?short_exclude

????????self.long_exclude?=?long_exclude

????????self.file_extend?=?file_extend

????def?__del__(self):

????????pass

????def?start(self,?func):

????????self.func?=?func

????????return?self.loop_file(self.root_dir)????

????def?loop_file(self,?root_dir):

????????t_sum?=?[]

????????sub_gen?=?os.listdir(root_dir)

????????for?sub?in?sub_gen:

????????????is_exclude?=?False

????????????for?extends?in?self.short_exclude:??##在不检查文件、目录范围中

????????????????if?extends?in?sub:??????????????##包含特定内容

????????????????????is_exclude?=?True

????????????????????break

????????????????if?re.search(extends,?sub):?????##匹配指定正则

????????????????????is_exclude?=?True

????????????????????break????????????????????

????????????if?is_exclude:

????????????????continue????????????

????????????abs_path?=?os.path.join(root_dir,?sub)

????????????is_exclude?=?False

????????????for?exclude?in?self.long_exclude:

????????????????if?exclude?==?abs_path[-len(exclude):]:

????????????????????is_exclude?=?True

????????????????????break

????????????if?is_exclude:

????????????????continue

????????????if?os.path.isdir(abs_path):

????????????????t_sum.extend(self.loop_file(abs_path))

????????????elif?os.path.isfile(abs_path):????????????

????????????????if?not?"."?+?abs_path.rsplit(".",?1)[1]?in?self.file_extend:??##不在后缀名?检查范围中

????????????????????continue

????????????????t_sum.append(self.func(abs_path))

????????return?t_sum????

if?'__main__'==__name__:

????root_dir?=?r'D:\harness\newshoppingcart\testcase\promo\single_promo'

????short_exclude?=?['.svn',?'.*_new.rb']?????###不包含检查的短目录、文件

????long_exclude?=?[]?????????????????????????###不包含检查的长目录、文件

????file_extend?=?['.rb']?????????????????????###包含检查的文件类型

????lf?=?loop_file(root_dir,?short_exclude,?long_exclude,?file_extend)

????for?f?in?lf.start(lambda?f:?f):

????????print?f

python 循环读一个文件

Python按行读文件

1. 最基本的读文件方法:

# File: readline-example-1.py

file = open("sample.txt")

while 1:

line = file.readline()

if not line:

break

pass # do something

一行一行得从文件读数据,显然比较慢;不过很省内存。

在我的机器上读10M的sample.txt文件,每秒大约读32000行

2. 用fileinput模块

# File: readline-example-2.py

import fileinput

for line in fileinput.input("sample.txt"):

pass

写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多……

3. 带缓存的文件读取

# File: readline-example-3.py

file = open("sample.txt")

while 1:

lines = file.readlines(100000)

if not lines:

break

for line in lines:

pass # do something

这个方法真的更好吗?事实证明,用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!

————————————————————————————————————————————————————————————

在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据:

# File: readline-example-5.py

file = open("sample.txt")

for line in file:

pass # do something

而在Python 2.1里,你只能用xreadlines迭代器来实现:

# File: readline-example-4.py

file = open("sample.txt")

for line in file.xreadlines():

pass # do something

python中怎么读取文件内容

用open命令打开你要读取的文件,返回一个文件对象

然后在这个对象上执行read,readlines,readline等命令读取文件

或使用for循环自动按行读取文件

python中isread函数么

文件对象(open() 函数的返回值)提供了read()函数可以按字节或字符读取文件内容,到底是读取字节还是字符,取决于使用 open() 函数打开文件时,是否使用了 b 模式,如果使用了 b 模式,则每次读取一个字节;反之,则每次读取一个字符。

read() 函数的基本语法格式如下:

file.read([size])

其中,file 表示打开的文件对象;size 作为一个可选参数,用于指定要读取的字符个数,如果省略,则默认一次性读取所有内容。

【例 1】采用循环读取整个文件的内容。

# a.txt 文件内容为:C语言中文网

f = open("a.txt", 'r', True)

while True:

# 每次读取一个字符

ch = f.read(1)

# 如果没有读到数据,跳出循环

if not ch:

break

# 输出ch

print(ch, end='')

f.close()

运行结果为:

C语言中文网

上面程序采用循环依次读取每一个字符(因为程序没有使用 b 模式),每读取到一个字符,程序就输出该字符。

正如从上面程序所看到的,当程序读写完文件之后,推荐立即调用 close() 方法来关闭文件,这样可以避免资源泄露(后续章节会详细介绍 close() 函数)。

注意,在调用 read() 函数读取文件内容时,成功读取的前提是在 open() 函数中使用 r 或 r+ 的模式打开文件,否则(比如将上面程序中 open()的打开模式改为 w),程序会抛出io.UnsupportedOperation异常:

Traceback (most recent call last):

File "C:\Users\mengma\Desktop\demo.py", line 4, in

ch = f.read(1)

io.UnsupportedOperation: not readable

【例 2】调用 read() 方法时不传入参数,该方法默认会读取全部文件内容。例如:

f = open("a.txt", 'r', True)

# 直接读取全部文件

print(f.read())

f.close()

运行结果为:

C语言中文网

read()函数抛出UnicodeDecodeError异常的解决方法

当使用 open() 函数打开文本文件时,默认会使用当前操作系统的字符集,比如 Windows 平台,open() 函数默认使用 GBK 字符集。因此,上面程序读取的 a.txt 也必须使用 GBK 字符集保存;否则,程序就会出现UnicodeDecodeError错误。

如果要读取的文件所使用的字符集和当前操作系统的字符集不匹配,则有两种解决方式:

使用二进制模式读取,然后用 bytes 的 decode() 方法恢复成字符串。

利用 codecs 模块的 open() 函数来打开文件,该函数在打开文件时允许指定字符集。

例如,下面程序使用二进制模式来读取文本文件:

# 指定使用二进制方式读取文件内容,a.txt 以 utf-8 编码存储

f = open("a.txt", 'rb', True)

# 直接读取全部文件,并调用bytes的decode将字节内容恢复成字符串

print(f.read().decode('utf-8'))

f.close()

上面程序在调用 open() 函数时,传入了 rb 模式,这表明采用二进制模式读取文件,此时文件对象的 read() 方法返回的是 bytes 对象,程序可调用 bytes 对象的 decode() 方法将它恢复成字符串。由于此时读取的 a.txt 文件是以 UTF-8 的格式保存的,因此程序需要使用 decode() 方法恢复字符串时显式指定使用 UTF-8 字符集。

下面程序使用 codes 模块的 open() 函数来打开文件,此时可以显式指定字符集:

import codecs

# 指定使用utf-8 字符集读取文件内容

f = codecs.open("a.txt", 'r', 'utf-8', buffering=True)

while True:

# 每次读取一个字符

ch = f.read(1)

# 如果没有读取到数据,则跳出循环

if not ch : break

# 输出ch

print (ch, end='')

f.close()

上面程序在调用 open() 函数时显式指定使用 UTF-8 字符集,这样程序在读取文件内容时就完全没有问题了。

(责任编辑:IT教学网)

更多

推荐CSS教程文章