Python读写CSV文件

CSV文件格式

CSV (逗号分隔值文件格式)

逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。

转自:CSV(逗号分隔值文件格式) - 百度百科

纯文本打开:中间有逗号分隔
以Excel方式打开:类似于表格,没有逗号分隔(逗号作为分隔符,但是不显示)

Python读写CSV文件

简单案例:

import csv

data = [
    ("测试1", '软件测试工程师'),
    ("测试2", '软件测试工程师'),
    ("测试3", '软件测试工程师'),
    ("测试4", '软件测试工程师'),
    ("测试5", '软件测试工程师'),
]
# write
filename = 'test.csv'
f = open(filename, 'w', encoding='UTF8')
writer = csv.writer(f)
for i in data:
    writer.writerow(i)
f.close()

# read
f = csv.reader(open(filename, 'r', encoding='UTF8'))
for i in f:
    print(i)

打印:

['测试1', '软件测试工程师']
[]
['测试2', '软件测试工程师']
[]
['测试3', '软件测试工程师']
[]
['测试4', '软件测试工程师']
[]
['测试5', '软件测试工程师']
[]

左边是WPS打开的,右边时notepad++打开的,发现莫名其妙多了一个空行。
在这里插入图片描述

我们直接在IDE中打开open方法(Ctrl+鼠标左键点击open即可打开该方法定义),看下该方法的定义(这里只看newline参数,省略了其他参数的介绍):

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
    """
    Open file and return a stream.  Raise OSError upon failure.
    
    ……
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    ……
    """
    pass

翻译下大概意思:

Newline控制通用换行符的工作方式(它只适用于文本
模式)。它可以是None'''\n''\r''\r\n'。它的工作原理是
如下:

*在输入时,如果newline为None,则通用换行模式为
启用。输入中的行可以以'\n''\r',或'\r\n'和
在返回给。之前,这些被翻译成'\n'
调用者。如果是",则启用通用换行模式
未翻译的结尾返回给调用者。如果它有任何
其他合法的值,输入行只在给定值结束
字符串,并将行结束符未翻译返回给调用者。

*在输出时,如果newline为None,则写入的任何'\n'字符均为
转换为系统默认的行分隔符os.linesep。如果
Newline为'''\n',不发生翻译。如果newline是any
对于其他合法值,任何'\n'字符都要翻译
到给定的字符串。

我们可以看到在输出时,如果没有定义时按照os.linesep进行输出的,我们看下这是啥:
(电脑是Windows,默认换行符为\r\n)

import os

print('os.linesep前面', os.linesep, 'os.linesep后面')

输出:

os.linesep前面 
 os.linesep后面

但是好像看不出啥东西,因为换行符 \r\n都 是不可打印字符,再试下:

import os

# print('os.linesep前面', os.linesep, 'os.linesep后面')
print(int(os.linesep))

输出报错了,但是我得到想要的了:

    print(int(os.linesep))
ValueError: invalid literal for int() with base 10: '\r\n'

然后后面百度发现原来直接在命令行是可以显示的,如下:

在这里插入图片描述

参考:https://www.cnblogs.com/jeancheng/p/13759550.html

也就是说默认情况下,\r\n 中的 \n 会被替换成系统的换行符,即\r\n,因此替换后就是\r\r\n

用notepad++打开文件,显示所有字符,是这样的(哦,果然是这样):
在这里插入图片描述

问题找到了,也可以进行处理了,文档中也有相关介绍,把它置为空字符串就行了newline=""

import csv

data = [
    ("测试1", '软件测试工程师'),
    ("测试2", '软件测试工程师'),
    ("测试3", '软件测试工程师'),
    ("测试4", '软件测试工程师'),
    ("测试5", '软件测试工程师'),
]
# write
filename = 'test.csv'
f = open(filename, 'w', encoding='UTF8', newline="")
writer = csv.writer(f)
for i in data:
    writer.writerow(i)
f.close()

# read
f = csv.reader(open(filename, 'r', encoding='UTF8'))
for i in f:
    print(i)

打印:

['测试1', '软件测试工程师']
['测试2', '软件测试工程师']
['测试3', '软件测试工程师']
['测试4', '软件测试工程师']
['测试5', '软件测试工程师']

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值