写入包含空白元素的 csv 文件。 Python / CSV
Write to a csv file with a blank element. Python / CSV
我正在尝试从页面中抓取元素。如果该元素(始终是中间名)不存在,我可以轻松地使用 try/except 在脚本中通过它...直到它尝试保存到 csv。我会收到 writerow 错误:NameError: name 'Middle' is not defined
我怎样才能将 'NA' 或空白字段保存到 csv 文件?
import csv
First = #site element for first name
Last = #site element for last name
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])
如果您的 try except 块中不存在中间部分,则它永远不会设置为任何内容(您 确实 应该考虑排除确切的错误)
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
因此,您尝试将 Middle
设置为存在的任何元素,如果该元素不存在,则忽略它。在您的异常块中,将 Middle
设置为 N/a 而不是仅打印 N/A:
try:
Middle = #site element for middle name
print(Middle)
except:
Middle = "N/A"
print('NA')
这会导致 middle 实际上分配了一些东西,因此它不会抛出您看到的错误。
如评论中所述,您应该在 try catch 块之外定义 middle 以避免范围错误:
import csv
First = #site element for first name
Last = #site element for last name
Middle = 'N/A' #this will be overwritten if Middle exists in the try except block below, otherwise it will be 'N/A'
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])
我正在尝试从页面中抓取元素。如果该元素(始终是中间名)不存在,我可以轻松地使用 try/except 在脚本中通过它...直到它尝试保存到 csv。我会收到 writerow 错误:NameError: name 'Middle' is not defined
我怎样才能将 'NA' 或空白字段保存到 csv 文件?
import csv
First = #site element for first name
Last = #site element for last name
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])
如果您的 try except 块中不存在中间部分,则它永远不会设置为任何内容(您 确实 应该考虑排除确切的错误)
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
因此,您尝试将 Middle
设置为存在的任何元素,如果该元素不存在,则忽略它。在您的异常块中,将 Middle
设置为 N/a 而不是仅打印 N/A:
try:
Middle = #site element for middle name
print(Middle)
except:
Middle = "N/A"
print('NA')
这会导致 middle 实际上分配了一些东西,因此它不会抛出您看到的错误。
如评论中所述,您应该在 try catch 块之外定义 middle 以避免范围错误:
import csv
First = #site element for first name
Last = #site element for last name
Middle = 'N/A' #this will be overwritten if Middle exists in the try except block below, otherwise it will be 'N/A'
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])