python怎么读文件(python 文件读)
python之文件读取
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
参数说明:
name:文件名称的字符串值
mode:只读r ,写入w,追加a,默认文件访问模式为r
buffering:寄存区缓存
0:不寄存
1:访问文件时会寄存行
1:寄存区的缓存大小
负值:寄存区的缓存大小则为系统默认
1、打开文件,获取文件描述符
2、操作文件描述符(读、写)
3、关闭文件
运行结果:
?运行结果:
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读写文件
读文件
? ? 1)使用open()方法打开文件,返回一个文件对象
? ? ? ? 原型:open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
? ? ? ? 举例:f = open('test.txt', 'r')
? ? ? ? test.txt表示文件路径(包含文件名,这个file参数可以是绝对或者相对路径)
? ??????r表示是读文本文件,rb是读二进制文本文件。(这个mode参数默认值就是r)
????2)使用close()方法关闭文件
? ??????f.close()
? ? ? ? 打开后的文件必须关闭,因为文件对象会占用系统资源,系统打开文件数量也就有限了
? ??3)打开文件时的异常处理
? ??????f=open('test.txt', 'r')
? ? ? ? f.read()
? ? ? ? f.close()
????????FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
????????文件读写时都有可能产生异常IOError(比如文件不存在),这样其后面的f.read(),f.close()就不会调用。为保证无论是否异常都可以关闭文件,一般使用try ... finally来处理:
? ??????try:
? ? ????????f = open('test.txt', 'r')
? ? ? ? ? ? f.read()
????????finally:
? ? ????????if f:
? ? ? ? ????????f.close()
????????但这种写法过于繁琐,所以Python引入了with语句来自动调用close()方法:
????????with open('test.txt', 'r') as f:
????????????f.read()
? ? 4)读文件 - read()、readline() 和 readlines()
????????read() 一次读取整个文件,它通常用于将文件内容放到一个字符串变量中。如果文件过大,内存不够,可以通过反复调用read(size)方法,每次最多读取size个字节的内容。
????????readline() 一次读取文件中一行内容,可反复调用
????????readlines() 一次读取所有内容并按行返回列表,该列表可以由for ... in ... 结构再进一步处理。
? ? ? ? 特别注意:
????????这三种方法是把每行末尾的'\n'也读进来了,如有需要就得我们手动去掉'\n'
????????with open('test.txt', 'r') as f:
? ? ????????list = f.readlines()
????????for i in range(0, len(list)):
? ? ????????list[i] = list[i].rstrip('\n')
写文件
? ? 1)写文件和读文件是一样的,唯一区别是open文件时,传入标识符不同,即'w'或者'wb'表示写文本文件或写二进制文件
????f = open('test.txt', 'w')
????f = open('test.txt', 'wb')
????f = open('test.txt', 'a')
? ? f.close()
? ? 特别注意:
? ? 1. 如果没有这个文件,会自动创建一个新文件;如果有,就会先把原文件的内容清空再写入;若不想清空原来的内容而是直接在后面追加新的内容,就用'a'这个模式
? ? 2. 写文件,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了。
? ??2)写文件 - write()、writelines()
? ??write()方法和read()、readline()方法对应,是将字符串写入到文件中。
????writelines()方法和readlines()方法对应,也是针对 列表 的操作。它接收一个 字符串列表 作为参数,将他们写入到文件中。
? ? 特别注意:
? ? 换行符不会自动的加入,需要显式的加入换行符。
? ??f = open('test.txt', 'w')
????f.writelines(["111\n", "222\n", "333\n"])
补充说明:
1)对于非默认编码(utf-8)的文件,需要open时添加encording参数,选择对应的编码方式
2)r+, w+, a+,可读可写
3)seek()方法,移动文件指针
seek(offset[, whence]) ,offset是相对于某个位置的偏移量。位置由whence决定,默认whence=0,从开头起;whence=1,从当前位置算起;whence=2相对于文件末尾移动,通常offset取负值。