pythonwith读取文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写

pythonwith读取文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写的第1张示图

1. 用Python读入规定目录下的txt文件中的部分内容

# filename: test.pyimport osusers = [] # 用来保存从文件中读取的数据for item in os.listdir('.'): # 遍历指定目录 if os.path.isfile(item) and item.endswith('.txt'): # 判断是否为.txt文件 f = open(item) # 打开文件 for line in f: # 读入文件的每一行 if line.startswith('用户名'): # 变量初始化 uid = age = sex = None elif line.startswith("用户id"): # 根据每行开始内容获取数据 uid = line.split()[1] elif line.startswith("年龄"): age = line.split()[1] elif line.startswith("性别"): sex = line.split()[1] users.append([uid, age, sex]) # 将所获得的数据以列表的形式追加到数组中 f.close() # 关闭文件print(users) # 打印数组内容# [['12345', '23', '男'], ['12346', '23', '男'], ['12347', '23', '男'], ['12348', '23', '男']]使用的数据文件:1.txt————用户名 abc————用户id 12345年龄 23性别 男————用户名 小张————用户id 12346年龄 23性别 男2.txt————用户名 张三————用户id 12347年龄 23性别 男————用户名 李四————用户id 12348年龄 23性别 男

2. python 如何直接读取局域网内的其他机器的文件内容到当前程序内存中

windows下有API.BOOL WINAPI ReadProcessMemory(In HANDLE hProcess,In LPCVOID lpBaseAddress,Out LPVOID lpBuffer,In SIZE_T nSize,Out SIZE_T *lpNumberOfBytesRead);

3. python读取某一段文本问题

withopen("D:/1.txt","r")asf:text=f.readlines()tag=1list1=[]forcontentintext:content=content.strip()ifcontent=="aaaaaaa":tag+=1iftag%2==0:list1.append(content)list1.append("aaaaaaa")printlist1

4. 如何用python读取文本中指定行的内容

1 利用python的readlines()函数: [python] view plain <strong><span style="font-size:24px;"> </span><span style="font-size:14px;">fobj = open(r'Ori.Data.txt','r') for line in fobj.readlines()[1000:] fobj.close()</span></strong> 2 利用 linecache[python] view plain <strong><span style="font-size:14px;"> import linecache print(linecache.getline(r'D:\z.txt',10))</span></strong> 3 读取10行到13行中的内容[python] view plain <span style="font-size:14px;"> <strong> lnum = 0 with open('pit.txt', 'r') as fd: for line in fd: lnum += 1; if (lnum >= 10) && (lnum <= 13): print line fd.close()</strong></span> 4 求文本的行数[python] view plain <span style="font-size:14px;"><strong> fobj = open('Ori_Data.txt','r') row_len = len(fobj.readlines()) </strong></span> [python] view plain <span style="font-size:14px;"><strong> </strong></span> [python] view plain <span style="font-size:14px;"><strong> fobj = open(filepath,'r') data = fobj.read() fobj.close() text_len = data.count('\n')<span style="font-family: Arial, Helvetica, sans-serif;"></span></strong></span>

5. python中with语句的作用

with语句相当于你定义一个类的时候定义了__enter__()和__exit__()这个两个方法。在我们进行文件操作的的时候会用到open方法,后面有了with open以后就不再只使用open方法了,为什么?因为with open方法简单,我们不用再去管关闭文件了,即使中间发生异常,with open也会帮我们把文件关闭掉,以下示例演示下with open方法;class File(object):"""文件操作类"""def __init__(self, filepath, mode):self.filepath = filepathself.mode = modedef __enter__(self):"""打开文件"""self.file = open(self.filepath, self.mode)print("打开文件")return self.filedef __exit__(self, exc_type, exc_val, exc_tb):"""关闭文件"""print("关闭文件")self.file.close()if __name__ == '__main__':with File('log.log', 'r') as file:file.write("家啊")可以看出来有了__enter__()和__exit__(),我们自定义的类也可以使用with了

6. python怎么读取json文件内容

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

JSON在python中分别由list和dict组成。

这是用于序列化的两个模块:

json: 用于字符串和python数据类型间进行转换

pickle: 用于python特有的类型和python的数据类型间进行转换

Json模块提供了四个功能:mps、mp、loads、load

pickle模块提供了四个功能:mps、mp、loads、load

json mps把数据类型转换成字符串 mp把数据类型转换成字符串并存储在文件中 loads把字符串转换成数据类型 load把文件打开从字符串转换成数据类型

json是可以在不同语言之间交换数据的,而pickle只在python之间使用。json只能序列化最基本的数据类型,josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。

事例:

mps:将python中的 字典 转换为 字符串

7. python with函数怎么用

with在python中并不是函数,是一个关键词语句,比如if就是关键词语句。with大多用来打开一个文档。比如: with open('test.txt') as f: f.read()这样就可以读取名为test的文档里的内容,并且使用with语句不需要我们手动再调用文件的close()方法来关闭文件,如果test.txt文档对象不再被使用,with会自动关闭文档。比较智能一点。

8. 请教一下大神如何用python读取图片的txt标签内容并将图片及对应标签移动至指定文件夹

import osdef search(s, path=os.path.abspath('.')):for z in os.listdir(path):if os.path.isdir(path + os.path.sep + z):print('Currnet:', path)path2 = os.path.join(path, z)print('future:', path2)search(s, path2)elif os.path.isfile(path + os.path.sep + z):if s in z:print(os.path.join(path, z))with open(path + os.path.sep + z, 'r') as fr:with open('save.txt', 'a') as fw:fw.write(path + '\t' + fr.read())search('csv', '.')

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

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

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

whileTrue:

line=f.readline()

ifline:

pass#dosomethinghere

line=line.strip()

p=line.rfind('.')

filename=line[0:p]

print"create%s"%line

else:

break

f.close()

未经允许不得转载:山九号 » pythonwith读取文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写

赞 (0)