改进这个代码def DelArealnfo(): import csv fo = open("景点信息表.csv", 'r') ls = [] for line in fo: line = line.replace('\n', '') ls.append(line.split(',')) fo.close() for ln in ls: for info in ln: print("{:10}\t".format(info), end='') print() print("以上是所有景点信息,请问您要删除哪个?") with open('景点信息表.csv',"r") as file: reader = csv.reader(file) rows = [] for row in reader: rows.append(row) q = int(input("请输入你想删除的景点的编号:")) s = [110001, 110002, 110003, 110004, 110005, 120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009] w = 1 while w == 1: if q == 110001: r = 1 return r elif q == 110002: r = 2 return r elif q == 110003: r = 3 return r elif q == 110004: r = 4 return r elif q == 110005: r = 5 return r elif q == 120001: r = 6 return r elif q == 120002: r = 7 return r elif q == 120003: r = 8 return r elif q == 120004: r = 9 return r elif q == 120005: r = 10 return r elif q == 120006: r = 11 return r elif q == 120007: r = 12 return r elif q == 120008: r = 13 return r elif q == 120009: r = 14 return r elif q not in s: print("请输入正确的景点编号!") w = w - 1 del rows[w] with open('景点信息表.csv', 'w', newline='',encoding="utf-8") as fileout: write = csv.writer(fileout) write.writerow(rows) print("已成功删除!") n = input("按1继续删除,按其他任意键返回主界面") if n == "1": DelArealnfo() else: main()
时间: 2023-06-09 22:03:23 浏览: 91
这段代码存在一些问题,主要是在删除操作时涉及到列表索引的操作,但是在代码中使用了固定的变量 w,其值未被修改过,因此无法实现删除操作。建议将代码进行修改,如下所示:
```python
import csv
def DelArealnfo():
with open("景点信息表.csv", 'r') as file:
reader = csv.reader(file)
rows = []
for row in reader:
rows.append(row)
for row in rows:
print("{:10}\t{:10}\t{:10}\t{:10}\t{:10}\t".format(row[0], row[1], row[2], row[3], row[4]))
q = input("请输入你想删除的景点的编号:")
flag = False
for i in range(len(rows)):
if rows[i][0] == q:
rows.pop(i)
flag = True
break
if flag:
with open('景点信息表.csv', 'w', newline='',encoding="utf-8") as fileout:
writer = csv.writer(fileout)
writer.writerows(rows)
print("已成功删除!")
n = input("按1继续删除,按其他任意键返回主界面")
if n == "1":
DelArealnfo()
else:
main()
else:
print("输入的景点编号不存在,请重新输入!")
DelArealnfo()
def main():
print("欢迎使用景点信息管理系统!")
while True:
print("1.查询景点信息 2.添加景点信息 3.删除景点信息 4.退出系统")
choice = input("请输入序号进行操作:")
if choice == "1":
queryArealnfo()
elif choice == "2":
AddArealnfo()
elif choice == "3":
DelArealnfo()
elif choice == "4":
print("谢谢使用,再见!")
break
else:
print("输入有误,请重新输入!")
if __name__ == '__main__':
main()
```
修改后的代码使用了列表的 pop() 方法来删除指定的行数据,并且使用了一个 flag 变量来标记是否找到了指定的行数据。建议在代码中增加注释以提高代码的可读性。
阅读全文