python读写操作
1. python读写文件,如何将内容添加在文件开头呢
# coding: utf8
import os
f = open('a.txt', 'r')
content = f.read() # 读取文件内容
f_new = open('b.txt', 'w')
f_new.write('look !') # 开头写入内容
f_new.write(content) # 写入原文件内容
f.close()
f_new.close()
os.remove('a.txt') # 移除老文件
os.rename('b.txt', 'a.txt') # 新文件命名为老文件名
·········································································
2. python 怎样对excle的列进行读写操作
python操作Excel读写--使用xlrd 一、安装xlrd模块 到python官网下载
3. python可以同时对文件进行读写操作吗
'w' 表示建立文件,如果存在就清空成空文件。'w+' 就是 'w' 加上读操作的版能力。'a' 是追加,权'a+' 就是 'a' 加上读操作的能力。'r' 是读取文件,'r+' 就是可读可写。
不过除非你真正明白你在做什么,不要同时读写文件,因为结果通常不是你想要的(特别是 Python 2 + Windows 还有你意想不到的行为)。
建议先阅读手册 man 3 fopen 及 man 2 open。
4. python 的读写操作指针到底怎么移动的
python 不像c, 没办法直接使用指针。指针就是内存地址。 python中,最接近指针的就是, id() 返回某个对象的唯一id,类似于地址了。
5. python 怎样对excle文件进行读写操作
分别进入到xlrd和xlwt文件中对setup.py进行安装,安装命令为setup.py install
进入python解释器,输入import xlwt,正常无报错即可
下面是我写的一个将Excle文件中的数据读取到普通文本中,和从普通文本写到Excel的一个互换程序:
[python] view plain
#encoding:utf8
import xlrd
import xlwt
class OperExcel():
#读取Excel表
def rExcel(self,inEfile,outfile):
rfile = xlrd.open_workbook(inEfile)
#创建索引顺序获取一个工作表
table = rfile.sheet_by_index(0)
#其他方式
#table = rfile.sheets()[0]
#table = rfile.sheet_by_name(u'Sheet1')
#获取整行,整列的值
table.row_values(0)
table.col_values(0)
#获取行数和列数
nrows = table.nrows - 1
ncols = table.ncols
#循环获取列表的数据
#for i in range(nrows):
# print table.row_values(i)
wfile = open(outfile,'w')
#获取第一列中的所有值
for i in range(nrows):
#table.cell(i,0).value获取某一单元格的值
wfile.write(table.cell(i,0).value.encode('utf8') + '\n')
wfile.close()
#将数据写入Excel表
def wExcel(self,infile,outEfile):
rfile = open(infile,'r')
buf = rfile.read().split('\n')
rfile.close()
w = xlwt.Workbook()
sheet = w.add_sheet('sheet1')
for i in range(len(buf)):
print buf[i]
sheet.write(i,0,buf[i].decode('utf8'))
w.save(outEfile)
if __name__ == '__main__':
t = OperExcel()
t.rExcel('test.xls','test')
t.wExcel('test','1.xls')
6. python3 文件读写 注意什么
open()函数返回一个File对象,并且最常用的用法是使用两个参数,open(filename,mode)
第一个参专数是文件名,第属二个参数表示文件的打开方式。只读方式打开可以使用'r',写文件可以使用'w'(这个选项会把当前文件夹中存在同名文件时将该文件擦除),'a'可以用来追加内容,任何内容都会被写入文件的末尾。'r+'会同时读写。mode参数是可选参数,如果没有的话,默认是'r'。
一般情况下,文件都是用文本模式打开的,也就意味着,文件读写都是使用某种编码的,末日呢情况下都是用utf-8编码。'b'会用二进制形式打开文件。这个时候,文件读写都是以字节的形式。
在文本模式下,默认会把平台相关的换行符(windows平台是\r\n,Linux平台是\n)转换成\n,在写文件时,会把\n转换成平台相关的字符写入。这种后台的操作对于文本会非常有用,但是对于二进制文件如jpeg或exe文件,则会破坏文件,因此在打开这类文件时千万要使用二进制模式打开。
7. 用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()
8. python怎么读写excel文件
最近用python处理一个小项目,其中涉及到对excel的读写操作,通过查资料及实践做了一下总结,以便以后用。
python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库。
1、#读取Excel
importxlrd
data = xlrd.open_workbook(excelFile)
table = data.sheets()[0]
nrows = table.nrows #行数
ncols = table.ncols #列数
for i in xrange(0,nrows):
rowValues= table.row_values(i) #某一行数据
for item in rowValues:
printitem
2、写Excel文件
'''往EXCEl单元格写内容,每次写一行sheet:页签名称;row:行内容列表;rowIndex:行索引;
isBold:true:粗字段,false:普通字体'''
defWriteSheetRow(sheet,rowValueList,rowIndex,isBold):
i = 0
style = xlwt.easyxf('font: bold 1')
#style = xlwt.easyxf('font: bold 0, color red;')#红色字体
#style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 设置Excel单元格的背景色为黄色,字体为粗体
forsvalue inrowValueList:
strValue = unicode(str(svalue),'utf-8')
ifisBold:
sheet.write(rowIndex,i,strValue,style)
else:
sheet.write(rowIndex,i,strValue)
i = i + 1
'''写excel文件'''
defsave_Excel(strFile):
excelFile = unicode(strFile,"utf8")
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet1',cell_overwrite_ok=True)
headList = ['标题1','标题2','标题3','标题4','总计']
rowIndex = 0
WriteSheetRow(sheet,headList,rowIndex,True)
fori inxrange(1,11):
rowIndex = rowIndex + 1
valueList = []
forj inxrange(1,5):
valueList.append(j*i)
WriteSheetRow(sheet,valueList,rowIndex,False)
wbk.save(excelFile)
style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;')
在设置上Excel单元格的背景色时,fore_colour支持的颜色是有限的,仅支持一下颜色
aqua 0x31
black 0x08
blue 0x0C
blue_gray 0x36
bright_green 0x0B
brown 0x3C
coral 0x1D
cyan_ega 0x0F
dark_blue 0x12
dark_blue_ega 0x12
dark_green 0x3A
dark_green_ega 0x11
dark_purple 0x1C
dark_red 0x10
dark_red_ega 0x10
dark_teal 0x38
dark_yellow 0x13
gold 0x33
gray_ega 0x17
gray25 0x16
gray40 0x37
gray50 0x17
gray80 0x3F
green 0x11
ice_blue 0x1F
indigo 0x3E
ivory 0x1A
lavender 0x2E
light_blue 0x30
light_green 0x2A
light_orange 0x34
light_turquoise 0x29
light_yellow 0x2B
lime 0x32
magenta_ega 0x0E
ocean_blue 0x1E
olive_ega 0x13
olive_green 0x3B
orange 0x35
pale_blue 0x2C
periwinkle 0x18
pink 0x0E
plum 0x3D
purple_ega 0x14
red 0x0A
rose 0x2D
sea_green 0x39
silver_ega 0x16
sky_blue 0x28
tan 0x2F
teal 0x15
teal_ega 0x15
turquoise 0x0F
violet 0x14
white 0x09
yellow 0x0D"""
另外一种方式是 用pyExcelerator
9. 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'])
(9)python读写操作扩展阅读:
python控制语句
1、if语句,当条件成立时运行语句块。经常与else, elif(相当于else if) 配合使用。
2、for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。
3、while语句,当条件为真时,循环运行语句块。
4、try语句,与except,finally配合使用处理在程序运行中出现的异常情况。
5、class语句,用于定义类型。
6、def语句,用于定义函数和类型的方法。
10. python文件操作
这是使用迭代器的方法读取文件内容,这种方法的好处是占用内存空间较少。如果你使用readlines,read方法,它们实际上将整个文件内容读取到内存中,虽然你也可以逐行输出,但是你也可以跳着输出的(列表)。而你的这种方法-迭代器是不能直接跨行输出的,也就是说,你每次真的只从文件中读了一行,并且必须逐行读取,因为每次只读一行,所以占用内存极少,推荐的使用方法。