def read1(file):                #this function will read and extract the first column of values from the
    with open(file,"r") as b:        # text allowing us to access it later in our main function
        list1 = list(b)
        lines = b.readlines()
        result1 = []
        for i in lines:
            result1.append(list1.split()[0])
    b.close
    return result1
x = read1("XRD_example1.txt")

Adakah kesalahan yang terlihat jelas?

0
jakeyp 30 Maret 2020, 00:18

1 menjawab

Jawaban Terbaik

Anda melakukan:

    list1 = list(b)
    lines = b.readlines()

Tapi baris pertama sudah membaca semua isi file Anda, tidak ada yang bisa dibaca di baris kedua.

def read1(file):                #this function will read and extract the first column of values from the
    with open(file,"r") as b:        # text allowing us to access it later in our main function
        lines = b.readlines()
        result1 = []
        for i in lines:
            result1.append(i.split()[0])
    # no need for close, when using 'with open()'
    return result1

Harus bekerja, atau bahkan lebih baik:

def read1(file):                
    with open(file,"r") as b: 
        return [i.split()[0] for i in b.readlines()]
0
Błotosmętek 29 Maret 2020, 21:22