Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从csv文件导入数据-为什么他们打印不同的内容?_Python_Python 3.x_Csv - Fatal编程技术网

Python 从csv文件导入数据-为什么他们打印不同的内容?

Python 从csv文件导入数据-为什么他们打印不同的内容?,python,python-3.x,csv,Python,Python 3.x,Csv,以下面的代码为例: import csv # import items with first row inputfile = open('price.csv', 'r') reader = csv.reader(inputfile) rows1 = [row for row in reader] # here # del first row rows2 = rows1[1:] print(rows2) 改变 rows1 = [row for row in reader] 进入 更改输出: #

以下面的代码为例:

import csv
# import items with first row
inputfile = open('price.csv', 'r')
reader = csv.reader(inputfile)
rows1 = [row for row in reader] # here
# del first row
rows2 = rows1[1:]
print(rows2)
改变

rows1 = [row for row in reader]
进入

更改输出:

# with 'reader'
[['6004', '240'], ['6004', '350'], ['6004', '350']]

# with 'inputfile'
['6004,240\n', '6004,350\n', '6004,350\n']

是什么原因造成的?或者说,原理是什么?

文件
对象是可编辑的。迭代
文件
对象
inputfile
将原始(未解析)行作为字符串对象返回

您可以构造一个
csv.reader
对象来解析这些行。
csv.reader
对象也是可编辑的,对其进行迭代将返回单个csv记录的字符串列表


因此,在
inputfile
上循环时得到的结果与在
reader上循环时得到的结果不同

当您通过迭代或使用类似于
readline
/
readlines
的函数来读取换行符时,Python不会去掉换行符。如果您的所有行都以换行符结尾,您可以手动将其剥离

另一件事是,
csv.reader
从文件对象读取行,并创建一个列表迭代器,其中每个列表包含在
或您设置的任何分隔符上拆分的行的值,同时考虑引用和其他细微差别

例如,要获得类似的行为,可以执行以下操作:

[row[:-1].split(',') for row in inputfile]

在迭代文件对象inputfile时,需要显式去除空白

rows1=[row.strip() for row in inputfile]

csv阅读器将每一行作为一个列表,用逗号分隔,而当您简单地读取文件时,每一行都是一个字符串。使用逗号拆分与
csv
模块的操作不同:特别是,csv文件可以包含带引号的值,这些值可以包含逗号字符。@DanielPryden。
rows1=[row.strip() for row in inputfile]