简体   繁体   English

在Python中读取文件中的数据

[英]Reading data from a file in Python

I have a data file that looks like this: 我有一个数据文件,看起来像这样:

1,100
2,200
3,-400
4,500

As you can see, each data point has 2 components When I do file.readlines() they all come up as strings such as '1,100\\n' so I am wondering how would I make them into integers? 如您所见,每个数据点都有2个组件。当我执行file.readlines()时,它们都以字符串形式出现,例如'1,100 \\ n',所以我想知道如何将它们变成整数?

This is comma separated data so using the csv module is a good approach. 这是逗号分隔的数据,因此使用csv模块是一种很好的方法。

Simple version to extract the string data 简单版本提取字符串数据

import csv
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for a, b in reader:
        print a, b

or with Thomas's approach to cast data to integers 或采用Thomas的方法将数据转换为整数

import csv
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for line in reader:
        a, b = map(int, line)
        print a, b

Read line by line and then split each line: 逐行读取,然后拆分每行:

with open('file.txt', 'r') as f:
    for line in f:
        a, b = [int(x) for x in line.split(',')]
        # here you can use a and b as numbers

The above has the advantage of using the with statement, which takes care of automatically closing the file even in the event of an error. 上面的优点是使用with语句,即使出现错误也可以自动关闭文件。

You might do: 您可以这样做:

map(int, line.strip().split(','))

Here's what this does 这是这样做的

  1. line.strip() converts "1,100\\n" to "1,100" line.strip()"1,100\\n"转换为"1,100"
  2. line.split(',') converts "1,100" to ("1", "100")` line.split(',') converts “ 1,100” line.split(',') converts to (“ 1”,“ 100”)`
  3. map(int, ...) applies int to each argument, and returns (1, 100) map(int, ...)int应用于每个参数,并返回(1, 100)

I would use numpy.loadtxt() for that: 我会为此使用numpy.loadtxt()

import numpy
numpy.loadtxt("yourFileName.txt", dtype=int, delimiter=",")

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

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