python循环写入文件
1. python中将列表中保存的二维数据通过循环用writelines写入文件为什么是错的
writeline写入的只能是字符串
不能是列表,你需要把列表转换为字符串然后写入
2. python如何实现for循环操作文件
python用for循环遍历文件操作,代码如下:
#!ursinenvpython
#encoding:utf-8#设置编码方式
importos
importre
classloop_file:
def__init__(self,root_dir,short_exclude=[],long_exclude=[],file_extend=[]):
self.root_dir=root_dir
self.short_exclude=short_exclude
self.long_exclude=long_exclude
self.file_extend=file_extend
def__del__(self):
pass
defstart(self,func):
self.func=func
returnself.loop_file(self.root_dir)
defloop_file(self,root_dir):
t_sum=[]
sub_gen=os.listdir(root_dir)
forsubinsub_gen:
is_exclude=False
forextendsinself.short_exclude:##在不检查文件、目录范围中
ifextendsinsub:##包含特定内容
is_exclude=True
break
ifre.search(extends,sub):##匹配指定正则
is_exclude=True
break
ifis_exclude:
continue
abs_path=os.path.join(root_dir,sub)
is_exclude=False
forexcludeinself.long_exclude:
ifexclude==abs_path[-len(exclude):]:
is_exclude=True
break
ifis_exclude:
continue
ifos.path.isdir(abs_path):
t_sum.extend(self.loop_file(abs_path))
elifos.path.isfile(abs_path):
ifnot"."+abs_path.rsplit(".",1)[1]inself.file_extend:##不在后缀名检查范围中
continue
t_sum.append(self.func(abs_path))
returnt_sum
if'__main__'==__name__:
root_dir=r'D:harness ewshoppingcart estcasepromosingle_promo'
short_exclude=['.svn','.*_new.rb']###不包含检查的短目录、文件
long_exclude=[]###不包含检查的长目录、文件
file_extend=['.rb']###包含检查的文件类型
lf=loop_file(root_dir,short_exclude,long_exclude,file_extend)
forfinlf.start(lambdaf:f):
printf
3. 使用python写文件时,如何做到写入文件由于外力删掉了之后可以新创建一个同名文件并继续写入
你的试验很详细。不过这个现象在linux下可能与windows下不一样。 通常改名或者是删除后文件就失效了。写入操作也是无效的。
为了防止别人修改你的文件,通常在写入时,会加上一个锁。使用操作系统特有的open方法才可以加锁。
可以使用portalocker,filelock 也可以使用posixfile,
os.open能不能成呢?按理可以。不过C语言里使用fopen没有这个功能,不过使用fcntl里的open可以。
你加了锁后,别人就不能写。文件处于占用状态。
另外操作系统都有一种文件监控机制的消息通知。具体忘记了。在unix与windows都有这个功能。当别人程序修改了某个文件,你会立刻得到消息通知。
补充一些教程。os.open还是可以用的。
os.open(file, flags[, mode]);
Parameters
file -- File name to be opened.
flags -- This is the following constants are options for the flags. They can be combined using the bitwise OR operator |. Some of them are not available on all platforms.
os.O_RDONLY: open for reading only
os.O_WRONLY: open for writing only
os.O_RDWR : open for reading and writing
os.O_NONBLOCK: do not block on open
os.O_APPEND: append on each write
os.O_CREAT: create file if it does not exist
os.O_TRUNC: truncate size to 0
os.O_EXCL: error if create and file exists
os.O_SHLOCK: atomically obtain a shared lock
os.O_EXLOCK: atomically obtain an exclusive lock
os.O_DIRECT: eliminate or rece cache effects
os.O_FSYNC : synchronous writes
os.O_NOFOLLOW: do not follow symlinks
mode -- This work in similar way as it works for chmod() method.
4. python写数据到文件一次只能写一个数据
python写数据到衫乎文件一次只能写一个数据原因如下:
1、代码在第一次循环中将中缓文件关闭了,因此后边的数据写不进去。
2、文件内容不完整,卖塌模要写入的数据内容依然在缓冲区中,没有写入文件。
5. 用python将内容写入文件,写入数据出现重复多次
代码file.open("file","a/r/w"),修改第二参数
a是添加内容到以前的文件最后面
r是只读无法写
w是重新写,把之前的内容全部覆盖的.
6. Python怎么把循环得到的结果按照列依次写入到一个csv文件中
我改了一下你的代码,实测是可以从 a.csv复制到 b.csv中
import csv
def foo():
with open('a.csv', 'r') as f:
reader = csv.DictReader(f)
rows = [row for row in reader]
if not rows:
return
with open('b.csv', mode='w', newline='', errors='ignore') as f2:
for index, row in enumerate(rows):
if index == 0:
f_csv = csv.DictWriter(f2, fieldnames=list(row.keys()))
f_csv.writeheader()
f_csv.writerow(row)
if __name__ == '__main__':
foo()
7. python 写入文件 只能写入一行
ft=open("a",'w')
try:
ft.write(' '.join(result))
except:
log.error('writebackuperror:'+JOBNAME)
finally:
ft.close()
os.chdir(basePath)
8. python可以同时对文件进行读写操作吗
对文件的操作,步骤为:打开一个文件-->读取/写入内容-->保存文件
文件读写的3中模式
# 1、w 写模式,它是不能读的,如果用w模式打开一个已经存在的文件,会清空以前的文件内容,重新写
# w+ 是读写内容,只要沾上w,肯定会清空原来的文件
# 2、r 读模式,只能读,不能写,而且文件必须存在
# r+ 是读写模式,只要沾上r,文件必须存在
# 3、a 追加模式,也能写,在文件的末尾添加内容
# 4、rb+、wb+、ab+,这种是二进制模式打开或者读取,一些音乐文件
test1.txt
1 如果无情的风摘走了那片树叶
2 如同摘走了我的心
3 在每一个想你的夜晚
4 请允许我将你抱紧
5 我不像一只大雁可以秋去春来
6 衔回丢失的缘分
7 所以从来不敢回忆离别
8 越是清晰 越是伤心
9 你说所有的城市没有不同
10 我宁愿相信你心中有片草原
1、循环读取文件中的每一行内容:
demo1.py1 file = open('test1.txt','r+')# 打开test1.txt 文件
2 for line in file: # 遍历file文件
3 print('line里面存放的是:',line) # 循环打印文件中每一行内容
4 print(type(line)) # <class 'str'> 类型是字符串
5 file.close()# 关闭文件
用with的方式打开文件,不用担心使用完文件后忘记关闭,它会自动将文件关闭1 with open('test1.txt','r+') as file:
2 for line in file:
3 print('line里面存放的是:',line) # 循环打印文件中每一行内容
4 print(type(line)) # <class 'str'> 类型是字符串
3、向文件中写入内容
1 with open('users','a+') as fw: # 打开文件
2 fw.write('写入文件内容')
4、用函数的方式读取文件
1 def read_file(filename):
2 '''
3 用来读取文件内容
4 :param filename: 文件名
5 '''
6 with open(filename,'a+') as fr:
7 fr.seek(0) # 移动文件指针
8 content = fr.read() # content 类型是字符串
9 print('content:',content)
10 read_file('users') # 调用函数
5、用函数的方式写文件
1 def write_file(filename,content):
2 '''
3 用来读取文件内容的
4 :param filename: 文件名
5 '''
6 with open(filename,'a+') as fw:
7 fw.seek(0) # 移动文件指针
8 fw.truncate() # 清空文件内容
9 fw.write(str(content))
10 write_file('a','hello world') # 调用函数