导入并编辑带有验证规则的CSV文件



我对Python/编码非常陌生,所以请原谅,如果这是一个简单的问题,我只是在努力寻找答案。

我的任务是使用Python创建一个非常简单的应用程序来导入CSV文件,并能够向文件添加数据或编辑数据。然而,我正在努力的是把验证规则。例如,在ID列中,它需要至少6个数字。

下面是我到目前为止得到的代码,它允许我导入文件,并能够编辑现有行,然后将其保存为新文件。这工作得很好,但正如我所说,我可以添加验证规则。如果是这样,我该如何处理呢?

import csv
myList = []
#2: Open my test file and populate list
with open ('Treasury_Faults.csv','r') as file:
myFile =csv.reader(file)
for row in myFile:
myList.append(row)
#3: Show content of file with row numbers for selection
print ("Please read the csv file data below:")
for i in range (len(myList)):
print ("Row " + str(i) + ": " + str(myList[i]))

#4: Select which row for editing
editRow = int(input("nWhich row would you like to change? Enter 1 - " + str(len(myList)-1) + " :"))
print ("Please enter the new details for each of the following :")
#5: Make changes and append the list
for i in range (len(myList[0])):
newDetails = input("Enter new data for " + str(myList[0][i]) + " :")
myList[editRow][i] = newDetails
#6: Display the new list to accept the changes made
print ("nPlease see the details of the new file below:")
for i in range (len(myList)):
print ("Row " + str(i) + " :" + str(myList[i]))
#7: Accept changes and save file
changeCSV = input ("nWould you like to make the changes to the csv file ? Y/N").lower()
if changeCSV == ("y"):
with open ('outputfile.csv','w+') as file:
myFile = csv.writer(file)
for i in range (len(myList)):
myFile.writerow(myList[i])

下面是文件

的示例

考虑使用openpyxl -一个Python库来读写Excel 2010 xlsx/xlsm文件

使用Openpyxl验证的例子:

>>> from openpyxl import Workbook
>>> from openpyxl.worksheet.datavalidation import DataValidation
>>>
>>> # Create the workbook and worksheet we'll be working with
>>> wb = Workbook()
>>> ws = wb.active
>>>
>>> # Create a data-validation object with list validation
>>> dv = DataValidation(type="list", formula1='"Dog,Cat,Bat"', allow_blank=True)
>>>
>>> # Optionally set a custom error message
>>> dv.error ='Your entry is not in the list'
>>> dv.errorTitle = 'Invalid Entry'
>>>
>>> # Optionally set a custom prompt message
>>> dv.prompt = 'Please select from the list'
>>> dv.promptTitle = 'List Selection'
>>>
>>> # Add the data-validation object to the worksheet
>>> ws.add_data_validation(dv)

最新更新