當前位置:首頁 » 編程語言 » python循環寫入文件

python循環寫入文件

發布時間: 2023-06-13 09:36:12

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將內容寫入文件,寫入數據出現重復多次

  1. 代碼file.open("file","a/r/w"),修改第二參數

  2. 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') # 調用函數

熱點內容
c語言矩陣的轉置 發布:2025-02-13 02:38:43 瀏覽:624
rowphp 發布:2025-02-13 02:37:16 瀏覽:711
光遇安卓服周年傘在哪裡領取 發布:2025-02-13 02:22:18 瀏覽:674
寫mv腳本軟體 發布:2025-02-13 02:21:56 瀏覽:696
超內核源碼 發布:2025-02-13 02:12:54 瀏覽:444
趣粉腳本 發布:2025-02-13 02:11:23 瀏覽:952
壓縮的茶葉怎麼弄開 發布:2025-02-13 02:11:16 瀏覽:739
n1ftp伺服器 發布:2025-02-13 02:10:39 瀏覽:348
沒有卡沒有密碼怎麼辦啊 發布:2025-02-13 01:51:53 瀏覽:461
linux2個ftp伺服器 發布:2025-02-13 01:44:31 瀏覽:15