📜  python csv reader set delimiter - Python(1)

📅  最后修改于: 2023-12-03 15:33:58.827000             🧑  作者: Mango

Python CSV Reader Set Delimiter

CSV (Comma Separated Values) is a file format used to store data in a tabular form, where each record or row is separated by a comma and each field or column within a record is separated by a delimiter. The delimiter used in CSV files can be a comma (,), tab (\t), or any other character.

When reading a CSV file in Python, we need to specify the delimiter used in the file. In this tutorial, we will see how to use the csv module in Python to read a CSV file with a custom delimiter.

Using csv.reader()

The csv.reader() method in Python's csv module is used to read CSV files. By default, it uses the comma (',') as the delimiter. To read a CSV file with a custom delimiter, we need to pass the delimiter as an argument to the csv.reader() method.

import csv

with open('file.csv') as file:
    reader = csv.reader(file, delimiter='|')
    for row in reader:
        print(row)

In the above code, we have opened a file named file.csv and passed it to the csv.reader() method. We have also specified the delimiter as '|', which means that the fields in the CSV file are separated by vertical bars.

The csv.reader() method returns an object that we can iterate over to get each row in the CSV file. We have used a for loop to iterate over the rows and print them to the console.

Using csv.DictReader()

The csv.DictReader() method in Python's csv module is used to read CSV files into a dictionary. Like the csv.reader() method, it also uses the comma (',') as the default delimiter. To read a CSV file with a custom delimiter, we need to pass the delimiter as an argument to the csv.DictReader() method.

import csv

with open('file.csv') as file:
    reader = csv.DictReader(file, delimiter='|')
    for row in reader:
        print(row['column1'], row['column2'])

In the above code, we have opened a file named file.csv and passed it to the csv.DictReader() method. We have also specified the delimiter as '|'.

The csv.DictReader() method returns a dictionary object for each row in the CSV file. We have used a for loop to iterate over the rows and print the values of column1 and column2.

Conclusion

In this tutorial, we have seen how to use the csv module in Python to read CSV files with custom delimiters using csv.reader() and csv.DictReader(). Remember to always specify the correct delimiter used in the CSV file, otherwise your program will not work as expected.