python读取文件列表(python如何读取文件中的数据)

http://www.itjxue.com  2023-04-12 05:57  来源:未知  点击次数: 

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 读取文本文件内容转化为python的list列表,案例如下:

1、目的

读取cal.txt内容,然后通过python脚本转化为list内容

2、文件内容

cal.txt

12

13

14

15

16

3、Python编写cal.py脚本内容

#!/usr/bin/python

#coding?=?UFT-8

result=[]

fd?=?file(?"cal.txt",?"r"?)

for?line?in?fd.readlines():

????result.append(list(map(int,line.split(','))))

print(result)

for?item?in?result:

????for?it?in?item:

???????print?it

4、执行转换为List列表结果内容:

[[12],?[13],?[14],?[15],?[16]]

12

13

14

15

16

python读取文件—txt文件常用读写操作

f = open("data.txt","r")? ?#设置文件对象

f.close() #关闭文件

为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代

with open('data.txt',"r") as f:? ? #设置文件对象

?str = f.read()()? ? #可以是随便对文件的操作

f = open("data.txt","r")? ?#设置文件对象

str = f.read()? ???#将txt文件的所有内容读入到字符串str中

f.close()? ?#将文件关闭

f = open("data.txt","r")? ?#设置文件对象

line = f.readline()

line = line[:-1]

while line:? ?? ?? ?? ? #直到读取完文件

? ? ?line = f.readline()??#读取一行文件,包括换行符

? ? ?line = line[:-1]? ???#去掉换行符,也可以不去

f.close() #关闭文件

data = []

for line in open("data.txt","r"): #设置文件对象并读取每一行文件

? ? ?data.append(line)? ?? ?? ?? ?? ?#将每一行文件加入到list中

?f = open("data.txt","r")? ?#设置文件对象

?data = f.readlines()??#直接将文件中按行读到list里,效果与方法2一样

?f.close()? ?? ?? ?? ? #关闭文件

可以使用pandas的.read_csv,读取文件的时候可以给每一列起名字,通过列名来调取相应列的数据。

import pandas as pd

data = pd.read_csv(" OSDO1012.txt",sep=',',header=None, names=['lat','lon','time','z']

使用data.lat就可以读取名为lat这一列的数据

?data = np.loadtxt("data.txt",skiprows = 1)? ?#将文件中数据加载到data数组里,并且跳过第一行

?with open('data.txt','w') as f:? ? #设置文件对象

? ? f.write(str)? ?? ?? ?? ?? ???#将字符串写入文件中

data = ['a','b','c']

单层列表写入文件

with open("data.txt","w") as f:

? ? f.writelines(data)

每一项用空格隔开,一个列表是一行写入文件

data =[ ['a','b','c'],['a','b','c'],['a','b','c']]

with open("data.txt","w") as f:? ? ? ? ? ? ? ? ? ? ? #设置文件对象

? ? ?for i in data:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #对于双层列表中的数据

? ? ? i = str(i).strip('[').strip(']').replace(',','').replace('\'','')+'\n'??#将其中每一个列表规范化成字符串

? ? ?f.write(i)? ? ? ? ? ? ? ? ? ? ? #写入文件

直接将每一项都写入文件

data =[ ['a','b','c'],['a','b','c'],['a','b','c']]

with open("data.txt","w") as f:? ? ? ? ? ? ? ? ? ? #设置文件对象

? ? ?for i in data:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #对于双层列表中的数据

? ? ? ? ? f.writelines(i)? ? ? ? ? ? ? ? ? ? ? ? ? ? #写入文件

np.savetxt("data.txt",data)? ???#将数组中数据写入到data.txt文件

np.save("data.txt",data)? ?? ???#将数组中数据写入到data.txt文件

python 读取txt文件到列表中

#-*-?coding:utf-8?-*-

f?=?open('123.txt',?'r')??????????????#文件为123.txt

sourceInLines?=?f.readlines()??#按行读出文件内容

f.close()

new?=?[]???????????????????????????????????#定义一个空列表,用来存储结果

for?line?in?sourceInLines:

????temp1?=?line.strip('\n')???????#去掉每行最后的换行符'\n'

????temp2?=?temp1.split(',')?????#以','为标志,将每行分割成列表

????new.append(temp2)??????????#将上一步得到的列表添加到new中

????

print?new

最后输出结果是:[['aaa',?'bbb',?'ccc'],?['ddd',?'eee',?'fff']],注意列表里存的是字符串'aaa',不是变量名aaa。

python文件读取与写入

open(filepath) :打开文件

open(filepath,'r') :打开方式,默认是读取

open(filepath).read() :读取文件中的内容

open(filepath).readline() :读取文件中一行的内容

open(filepath).readline()[1] :读取文件中的内容,返回值是列表。

open(filepath).close() :关闭文件

open(filepath).seek(0) :将光标回到首位

with open()函数,不用close()方法,默认自动关闭,所以需要制定一些规则.

文件内建函数和方法:

open() : 打开文件

read() :输入

readline() :输入一行

seek() :文件内移动

write() :输出

close() :关闭文件

Python文件操作有哪些方式?

Python文件操作主要有以下几种方式:

打开文件:使用open()函数打开文件,该函数需要指定文件名以及打开文件的模式(例如只读、只写、追加等)。打开文件后,可以使用文件对象进行读取、写入、关闭等操作。

读取文件:使用文件对象的read()、readline()、readlines()方法来读取文件内容。read()方法可以一次性读取整个文件,readline()方法可以逐行读取文件,readlines()方法可以将文件的所有行读取到一个列表中。

写入文件:使用文件对象的write()方法将数据写入文件。write()方法可以接受字符串作为参数,并将其写入文件。

关闭文件:使用文件对象的close()方法关闭文件。关闭文件后,可以避免占用系统资源。

with语句:使用with语句可以自动管理文件的关闭。with语句创建一个上下文环境,在该环境中打开文件,并在代码块执行完毕后自动关闭文件。

os模块:使用os模块可以进行文件和目录的操作,包括创建、重命名、删除、移动等。os模块还提供了一些与文件路径相关的函数,例如join()、split()、abspath()等,可以方便地处理文件路径。

(责任编辑:IT教学网)

更多