简体   繁体   English

Csv readlines 问题

[英]Csv readlines issue

I'm trying to readlines of a csv file file.我正在尝试读取 csv 文件文件的行。 The code to read the file in python with readlines and csv.reader works fine on windows but on Linux test server I am getting some issue maybe because of the \\n at the end of each line.使用 readlines 和 csv.reader 在 python 中读取文件的代码在 Windows 上运行良好,但在 Linux 测试服务器上,我遇到了一些问题,可能是因为每行末尾的\\n

Is there some difference in reading lines through readlines function in python on windows and linux?在 windows 和 linux 上通过 python 中的 readlines 函数读取行有什么区别吗?

This is my code:这是我的代码:

with open(r"C:\Users\prate\Downloads\meal_count_avg_meal.csv","r") as filemy:
    #mycontent=csv.reader(filemy)
    out = filemy.readlines()

Normally, you would read the CSV file in a row at a time, and carry out any required processing (eg converting to ints or floats ).通常,您会一次连续读取 CSV 文件,并执行任何所需的处理(例如转换为intsfloats )。 It is though possible to read all of your rows as a list of rows, with each row holding a list of the values:虽然可以将所有行作为行列表读取,每一行都包含一个值列表:

import csv

filename = r"C:\Users\prate\Downloads\meal_count_avg_meal.csv"

with open(filename, "rb") as file_my:
    csv_my = csv.reader(file_my)
    # next(csv_my)     # Optionally skip the header
    rows = list(csv_my)

As you are still using Python 2.x, you will need to open your file with rb , which is required for the csv.reader() object.由于您仍在使用 Python 2.x,您将需要使用rb打开您的文件,这是csv.reader()对象所必需的。 This approach should give you the same result on Windows or Linux.这种方法应该在 Windows 或 Linux 上给你相同的结果。

rows would be something like: rows是这样的:

[["header1", "header2", "header3"], ["value1", "value2", "value3"]]

This assumes your CSV file is a standard commas separated variable format.这假设您的 CSV 文件是标准的逗号分隔变量格式。 If your CSV file contains a header, and you don't want that included in rows , then simply add the following:如果您的 CSV 文件包含一个标题,并且您不希望它包含在rows ,那么只需添加以下内容:

next(csv_my)

Using .readlines() will keep the line endings (which are different on Windows and Linux).使用.readlines()将保留行尾(在 Windows 和 Linux 上不同)。


If one of your environments is Python 3.x, it would need to changed as follows:如果您的环境之一是 Python 3.x,则需要进行如下更改:

import csv

filename = r"C:\Users\prate\Downloads\meal_count_avg_meal.csv"

with open(filename, "r", newline="") as file_my:
    csv_my = csv.reader(file_my)
    # next(csv_my)     # Optionally skip the header
    rows = list(csv_my)

If you plan on running the same code on 2.x and 3.x unchanged, your code would have to test which version you are running on and open the file differently depending on the version.如果您计划在 2.x 和 3.x 上运行相同的代码而保持不变,您的代码必须测试您正在运行的版本并根据版本以不同的方式打开文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM