python如何读取文件的内容

Python014

python如何读取文件的内容,第1张

# _*_ 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语句,用于定义函数和类型的方法。

path = 'your dir'

for dirpath, dirs, files in os.walk(path):

print '1',dirpath

print '2',dirs

print '3',files

for file in files:

z_path = os.path.join(dirpath, file)

print z_path

python循环遍历excel总是出现表头的解决办法。

1、找出当前工作目录中的所有CSV文件。

2、跳过第一行,将内容写入一个新的CSV文件。

3、循环遍历从os.listdir()得到的文件列表,跳过非CSV文件。

4、创建一个CSVReader对象,读取该文件的内容,利用line_num属性确定要跳过哪一行。

5、创建一个CSVWriter对象,将读入的数据写入新文件。针对这个项目,打开一个新的文件编辑器窗口,并保存为removeCsvHeader.py。