43.md 2.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 创建并读取 csv

> 原文: [https://pythonspot.com/files-spreadsheets-csv/](https://pythonspot.com/files-spreadsheets-csv/)

电子表格通常会导出 CSV(逗号分隔值)文件,因为它们易于读写。 CSV 文件仅由值,逗号和换行符组成。 该文件称为“逗号分隔值”文件,但您可以使用其他分隔符,例如竖线字符。

## 用 Python 创建电子表格文件(CSV)

让我们使用 Python 创建 CSV 格式的文件。 我们将使用逗号作为分隔符或除法符。

```py
import csv

with open('persons.csv', 'wb') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(['Name', 'Profession'])
    filewriter.writerow(['Derek', 'Software Developer'])
    filewriter.writerow(['Steve', 'Software Developer'])
    filewriter.writerow(['Paul', 'Manager'])

```

W
wizardforcel 已提交
24
运行此代码将为我们提供以下内容的`filpeople.csv`
W
init  
wizardforcel 已提交
25 26 27 28 29 30 31 32 33

```py
Name,Profession
Derek,Software Developer
Steve,Software Developer
Paul,Manager

```

W
wizardforcel 已提交
34
您可以在您喜欢的 Office 程序中导入`person.csv`文件。
W
init  
wizardforcel 已提交
35 36 37

![python csv](img/f177725bc03d4c71b4a00e1334990e57.jpg)

W
wizardforcel 已提交
38
用 Python 创建的电子表格文件
W
init  
wizardforcel 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

## 读取电子表格文件(csv)

如果您创建了 csv 文件,则可以使用以下代码逐行读取文件:

```py
import csv

# open file
with open('persons.csv', 'rb') as f:
    reader = csv.reader(f)

    # read file row by row
    for row in reader:
        print row

```

这将简单地将每一行显示为列表:

```py
['Name', 'Profession']
['Derek', 'Software Developer']
['Steve', 'Software Developer']
['Paul', 'Manager']

```

W
wizardforcel 已提交
67
也许您想将其存储到 Python 列表中。 我们从 csv 文件中获取数据,然后将其存储到 Python 列表中。 我们使用`if`语句跳过标题,因为它不属于列表。 完整代码:
W
init  
wizardforcel 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

```py
import csv

# create list holders for our data.
names = []
jobs = []

# open file
with open('persons.csv', 'rb') as f:
    reader = csv.reader(f)

    # read file row by row
    rowNr = 0
    for row in reader:
        # Skip the header row.
        if rowNr >= 1:
            names.append(row[0])
            jobs.append(row[1])

        # Increase the row number
        rowNr = rowNr + 1

# Print data 
print names
print jobs

```

结果:

```py
['Derek', 'Steve', 'Paul']
['Software Developer', 'Software Developer', 'Manager']

```

W
wizardforcel 已提交
105
大多数电子表格或 Office 程序都可以导出 csv 文件,因此我们建议您创建任何类型的 csv 文件并进行处理 :-)
W
init  
wizardforcel 已提交
106