我正在遵循 SO User "qmorgan" here提到的代碼,基本上,如果檔案不存在,我正在嘗試創建新的文本檔案。如果檔案存在,則覆寫現有檔案。為此,我的代碼如下所示。我面臨的問題是使用“a”來撰寫檔案,它是附加文本而不是覆寫它。因為'a'功能是在第一個if條件下附加文本。如果我使用“W”而不是“a”,那么它只會寫入最后一條記錄,而不是所有記錄。
在此先感謝您的幫助和努力!
Python代碼
filename='test.txt'
tables=["schema.table1","schema2.table2"]
for table in tables:
cur.execute (f'select count(*) from {table};')
result=cur.fecthone()
count=result[0] if result else 0
for row in result:
if os.path.exists(filename):
append_write='a'
my_file.close()
else:
append_write='w '
my_file=open(filename,append_write)
my_file.write(f"the table {table} contained {count} rows. \n")
my_file.close()
uj5u.com熱心網友回復:
只需在開始時打開檔案一次,而不是為每個查詢單獨打開。然后你可以簡單地使用w模式來覆寫它。
也不需要for row in result:回圈,因為您從不row在任何地方使用。result是一個只有一個元素的元組,由 回傳的計數COUNT(*),沒有其他東西可以回圈。
filename='test.txt'
tables=["schema.table1","schema2.table2"]
with open(filename, 'w') as my_file:
for table in tables:
cur.execute(f'select count(*) from {table};')
(count,) = cur.fetchone()
my_file.write(f"the table {table} contained {count} rows. \n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/478857.html
標籤:Python python-3.x 操作系统 文本文件 写
