因此,我正在运行一个脚本,该脚本为60个不同的项目提取数据,为了易于使用,我想将此数据存储在一个csv文件中。每次运行脚本时,我要存储所有60个项目,然后覆盖所有以前的数据。当我现在使用'w'参数运行它时,它只会添加它拉出的最后一项。如果我将其更改为“ a”,它将添加所有60个项目,但是当我下次运行它时,它不会覆盖。任何帮助表示赞赏!
import os, random, csv
vin = '1600'
n = 1
for path, subdirs, files in os.walk(r'\\sorion-app01\Shares\ProcessData\Broadcasts\Good'):
for filename in files:
if not 'XX' or not '0X' or not 'XXXXXX' or not '000X' in filename:
f = os.path.join(path, filename)
vins = str(f)[50:67]
if not 'X' in vins[13:17]:
vin = int(vins[13:17])
if vin > 1600:
from sys import platform
import pyodbc
if platform == "linux" or platform == "linux2":
print("linux")
driver = 'mydriver.so'
conn = pyodbc.connect(
driver = driver,
TDS_Version = '7.2', # Use for
server = 'aserver',
port = 1433,
database = 'TraceDB',
uid = 'EXTUser',
pwd = 'EXTPass!')
elif platform == "win32":
#print("Win32")
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=database')
#pull the data here#
with open('file.csv', 'w', newline='') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator = '\n',)
header = [('column1'), ('column1'), ('column2'), ('column3'), ('column4'), ('column5')]
if not csvfile:
filewriter.writeheader(header)
filewriter.writerow([data, data2, data3, data4, data5, data6])
n=n+1
答案 0 :(得分:3)
这是因为您每次在循环中都要重新打开文件;您想在循环之前打开它,然后在循环之后关闭它。
答案 1 :(得分:2)
在代码的开头将其覆盖为空文件对您有用吗?
sudo apt update
sudo apt install snapd
最好!