python怎么读取文件名的内容

python读取文件内容的方法:
一.最方便的方法是一次性读取文件中的所有内容并放置到一个大字符串中:
all_the_text = open('thefile.txt').read( )
# 文本文件中的所有文本
all_the_data = open('abinfile','rb').read( )
# 二进制文件中的所有数据
为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。举个例子,对文本文件读取:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
不一定要在这里用Try/finally语句,但是用了效果更好,因为它可以保证文件对象被关闭,即使在读取中发生了严重错误。
二.最简单、最快,也最具Python风格的方法是逐行读取文本文件内容,并将读取的数据放置到一个字符串列表中:
list_of_all_the_lines = file_object.readlines( )
这样读出的每行文本末尾都带有"\n"符号;如果你不想这样,还有另一个替代的办法,比如:
list_of_all_the_lines = file_object.read( ).splitlines( )
list_of_all_the_lines = file_object.read( ).split('\n')
list_of_all_the_lines = [L.rstrip('\n') for L in file_object]
最简单最快的逐行处理文本文件的方法是,用一个简单的for循环语句:
for line in file_object:
process line
这种方法同样会在每行末尾留下"\n"符号;可以在for循环的主体部分加一句:
lineline = line.rstrip('\n')
或者,你想去除每行的末尾的空白符(不只是'\n'\),常见的办法是:
lineline = line.rstrip( )

❷ python怎么将本地一个文件夹的所有文本读进内存中

列出文件,把各个文件打开读到bytes字节串里面.
比如
f=open("a.txt","rb")
a={}
a["a.txt"]=f.read()
f=open("b.txt","rb") #写成对列版表的循环权
a["b.txt"]=f.read()
f=open("c.txt","rb") #写成对列表的循环
a["c.txt"]=f.read()

❸ 使用python如何读取本地json文件

具体情况具体分析,要看你的文件是什么编码,用的python哪个版本

❹ Python如何读写文本文件

1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
2.读文件读文本文件input = open('data', 'r')
#第二个参数默认为r
input = open('data')

读二进制文件input = open('data', 'rb')
读取所有内容file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
读固定字节file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
读每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:
process line
3.写文件写文本文件output = open('data.txt', 'w')
写二进制文件output = open('data.txt', 'wb')
追加写文件output = open('data.txt', 'a')

output .write("\n都有是好人")

output .close( )

写数据file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

❺ Python 读取文本文件,怎么才能读取一段内容

python读取段落需要自定义函数:
from _ _future_ _ import generators

def paragraphs(fileobj, separator='\n'):
if separator[-1:] != '\n': separator += '\n' paragraph = []
for line in fileobj:
if line == separator:
if paragraph: yield ''.join(paragraph)
paragraph = []
else: paragraph.append(line)
if paragraph: yield ''.join(paragraph)

❻ 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'])

(6)python读取本地文件扩展阅读:

python控制语句

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

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

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

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

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

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

❼ python如何打开本地文件我哪里有问题,刚学编程的。大家帮忙看看了,多谢!

A=open(r'xxxxxx','r')
fortxtinA.readlines():
print(txt)
A.close()

❽ python怎么读取TXT

Python的文本处理是经常碰到的一个问题,Python的文本文件的内容读取中,有三类方法:read()、readline()、readlines(),这三种方法各有利弊,下面逐一介绍其使用方法和利弊。

read():

  • read()是最简单的一种方法,一次性读取文件的所有内容放在一个大字符串中,即存在内存中

    file_object = open('test.txt') //不要把open放在try中,以防止打开失败,那么就不用关闭了try:
    file_context = file_object.read() //file_context是一个string,读取完后,就失去了对test.txt的文件引用
    # file_context = open(file).read().splitlines()
    // file_context是一个list,每行文本内容是list中的一个元素finally:
    file_object.close()//除了以上方法,也可用with、contextlib都可以打开文件,且自动关闭文件,//以防止打开的文件对象未关闭而占用内存
  • read()的利端:

  • 方便、简单

  • 一次性独读出文件放在一个大字符串中,速度最快

  • read()的弊端:

  • 文件过大的时候,占用内存会过大

  • readline():

  • readline()逐行读取文本,结果是一个list

    with open(file) as f: line = f.readline() while line:
    print line
    line = f.readline()
  • readline()的利端:

  • 占用内存小,逐行读取

  • readline()的弊端:

  • 由于是逐行读取,速度比较慢

  • readlines():

  • **readlines()一次性读取文本的所有内容,结果是一个list

    with open(file) as f: for line in f.readlines():
    print line
  • 这种方法读取的文本内容,每行文本末尾都会带一个' '换行符 (可以使用L.rstrip(' ')去掉换行符)

  • readlines()的利端:

  • 一次性读取文本内容,速度比较快

  • readlines()的弊端:

  • 随着文本的增大,占用内存会越来越多

  • 最简单、最快速的逐行处理文本的方法:直接for循环文件对象

  • file_object = open('test.txt','rU')try:

  • for line in file_object:

  • do_somthing_with(line)//line带" "finally:

  • file_object.close()

❾ python怎么读取txt文件全部数据

Python 读写文本文件

首先需要注意的是,txt文件是具有字符编码的,不同的txt字符编码可能不同。具体是什么编码,可以用 notepad++ 等文本编辑器查看。

读取文件建议使用 with...as... 结构,可以自动关闭文件。

withopen("text.txt","r")asf:
text=f.read()
print(text)

如果不用 with...as... 则必须手动关闭文件:

f=open("text.txt","r")
text=f.read()
f.close()
print(text)

如果读取的文件含有中文,使用内置的open可能会报错,这个时候要用到codecs模块:

importcodecs
withcodecs.open("text.txt","r",encoding="utf-8")asf:
text=f.read()
print(text)

(假设 text.txt 是 utf-8 编码)