要从 CSV 文件读取数据,请使用 Python CSV 库。下面是一个示例:
import csv # Open the CSV file for reading with open("test.csv", "rt") as f: # Create a CSV reader object reader = csv.reader(f, delimiter=",", quotechar='"') # Iterate over the rows in the CSV file for row in reader: print(row)
要将数据写入 CSV 文件,还可以使用 Python CSV 库:
import csv # Create a list of data to write to the CSV file data = [ (1, "A towel", 1.0), (42, " it says, ", 2.0), (1337, "is about the most ", -1), (0, "massively useful thing ", 123), (-2, "an interstellar hitchhiker can have.", 3), ] # Open the CSV file for writing with open("test.csv", "wt") as f: # Create a CSV writer object writer = csv.writer(f, delimiter=",", quotechar='"') # Write the data to the CSV file writer.writerows(data)
使用 CSV 时文件:
以下是示例代码的输出:
1,"A towel,",1.0 42," it says, ",2.0 1337,is about the most ,-1 0,massively useful thing ,123 -2,an interstellar hitchhiker can have.,3
以上是如何在Python中读写CSV文件?的详细内容。更多信息请关注PHP中文网其他相关文章!