Py学习  »  Python

python csv文件读取和保存

DeltaTroz • 4 年前 • 673 次点击  

我有一个关于保存最新的座位更新到我的csv文件的问题。 我希望用户预订的每个座位都能收到csv文件中的更改。 示例:如果用户预订a1座位,a1 is csv文件将替换为x。

我的程序目标是读取csv文件并将其存储,然后稍后对其进行替换。每排有5个座位。A1-A5为第一排商务舱,B1-B5为第二排商务舱。我希望这个程序能用x代替已被占用/预订的座位。 示例:A1 X A3 A4 A5(A2不可用,已占用)

这是我的代码:

seat =[]
csvfile = open('coba.csv') 
seating = csv.reader(csvfile)
for line in seating:
    seat.append(line)

print("Buy seat ?")
answer_1 = input("Answer : ")
if (answer_1 == "yes"):
    answer_2 = input("Enter preferred seat: ")
    if (answer_2 == "A1"):
        row = 1
        column = 0
        seat[row][column] = "X"
        for line in seat:
            print(' | '.join(line))
        writer = csv.writer(open('coba.csv', 'w'))
        writer.writerows(line)

我的CSV文件:

[Business]
A1,A2,A3,A4,A5
B1,B2,B3,B4,B5
[Economy]
C1,C2,C3,C4,C5
D1,D2,D3,D4,D5
E1,E2,E3,E4,E5

错误:

权限错误:[errno 13]权限被拒绝:“coba.csv”

提前谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47254
 
673 次点击  
文章 [ 5 ]  |  最新文章 4 年前
hygull
Reply   •   1 楼
hygull    5 年前

这只是修复代码。你可以在 object of type '_csv.reader' has no len(), csv data not recognized 是的。

有一个更好的解决方案,你正在寻找什么。

如何修复?

  • 初始化 seat 作为 [] 我们知道那个元组 () 是不变的。

  • seating 是一个迭代器,因此如果您希望计算长度,请将其转换为列表。

眼镜蛇

import csv 

def load():
    seat = []
    csvfile = open('coba.csv') 
    seating = csv.reader(csvfile)
    print(type(seating))

    seating = list(seating)
    print(type(seating))

    for line in seating:
        print(seating)
        if len(line[0].split(',')) == 5:
            #print(' | '.join(row))
            seat.append(line)

    print(seat)

load()

"""
<class '_csv.reader'>
<class 'list'>
[['[BUSINESS]'], ['A1,A2,A3,A4,A5'], ['B1,B2,B3,B4,B5']]
[['[BUSINESS]'], ['A1,A2,A3,A4,A5'], ['B1,B2,B3,B4,B5']]
[['[BUSINESS]'], ['A1,A2,A3,A4,A5'], ['B1,B2,B3,B4,B5']]
[['A1,A2,A3,A4,A5'], ['B1,B2,B3,B4,B5']]
"""
irrgit
Reply   •   2 楼
irrgit    5 年前

用每行的列表填充座位列表

seats = []
with open('file.csv', 'rb') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    for row in csvreader:
        line = tuple(row)
        if len(line) == 5:
            seat.append(list(line))

浏览列表中的每一行并将其更改为所需的内容。

Abdulrahman Bres
Reply   •   3 楼
Abdulrahman Bres    5 年前

第一行在csv中作为行无效的问题

(使用熊猫)这样做:

import pandas as pd

df = pd.read_csv('coba.csv', header=None, skiprows=[0], sep=',')

print(df)

或者可以跳过阅读代码的第一行。

Ali.Turkkan
Reply   •   4 楼
Ali.Turkkan    5 年前

这给出了A列的前5行:

from pandas import read_csv

data = read_csv('name.csv')

result = []

for i in range(5):
    result.append(data['A1'][i])
sipp11
Reply   •   5 楼
sipp11    5 年前

我想你有错别字。你应该检查一下 len(line) 而不是 len(seating) 同时使用list而不是tuple seat

import csv

def load():
    seat = []
    csvfile = open('x.csv')
    seating = csv.reader(csvfile)
    for line in seating:
        if len(line) == 5:
            seat.append(line)
    print(seat)

load()