从文本文件中读取并在python中打印字母数字值

时间:2015-07-26 17:26:37

标签: python numpy alphanumeric

我有一个文本文件,其前两列包含字母数字值。我想将它们存储在一个变量中并在之后打印出来。谁能告诉我如何在Python中这样做? 我试过用这个

1 [3]
2 [0]
2 [1]
2 [3]
1 [0, 2]
2 [2]
1 [4]
1 [1]

然后在forloop中:

表示范围内的i(0,len(x2)-1):        f1.write("%s"%(x2 [i]))

iau1.txt ab12 98ji ab13 98jj     。     。     

1 个答案:

答案 0 :(得分:0)

作为使用NumPy的替代方法,您还可以使用标准Python CSV库,如下所示:

import csv

# Load all rows from the file into a variable called rows
with open("iau1.txt", "r") as f_input:
    csv_reader = csv.reader(f_input, delimiter=" ", skipinitialspace=True)
    rows = list(csv_reader)

# Write the first two columns back to a different file and display it
with open("iau1_out.txt", "wb") as f_output:
    csv_writer = csv.writer(f_output, delimiter=" ")

    for cols in rows:
        csv_writer.writerow(cols[:2])
        print cols[0], cols[1]

假设输入文件格式如下:

ab12 98ji 111 222 333 444
ab13 98jj aaa bbb ccc ddd

输出文件将包含:

ab12 98ji
ab13 98jj

使用Python 2.7进行测试。

注意,将整个文件读入内存通常适用于小文件,但如果文件较大,您可能需要考虑按时处理此行:

with open(r"iau1.txt", "r") as f_input, open(r"iau1_out.txt", "wb") as f_output:
    csv_reader = csv.reader(f_input, delimiter=" ", skipinitialspace=True)
    csv_writer = csv.writer(f_output, delimiter=" ")

    for cols in csv_reader:
        csv_writer.writerow(cols[:2])
        print cols[0], cols[1]