我有一个.txt文件目录
每个.txt文件具有相同的格式,我只对目录中每个.txt文件的第一行的特定列范围感兴趣。
我尝试使用read(150-139)(其中那些数字代表我感兴趣的列范围)和readline()。
read(150-139)遇到的问题是它输出整个.txt文件或引发UnicodeDecodeError。
readline()遇到的问题是它引发了UnicodeDecodeError。
请注意:目录中每个.txt文件的列范围都是可读字符,每个文件的ANSI编码。 [泥浆,样品,电阻率,中子或伽玛]。
目标:将目录中所有.txt文件中相同列范围的字符追加到列表中-> lst_2
代码:
import os
#import numpy as np
#A string array containing all file names in a directory
names = os.listdir('c:\\users\Admin\Documents\Exm_3')
lst=[]
lst_2=[]
for name in names:
if name.endswith(".txt"):
lst.append(name)# append the names
with open(os.path.join('c:\\users\Admin\Documents\Exm_3', name)) as file:
c = file.read(150 - 139)
lst_2.append(c)
print(lst)
print(lst_2)
输出:
['j.txt', 'n.txt', 'q.txt', 'test.txt', 'y.txt']
['A2D 3.1.0 C', 'A2D 3.1.0 C', 'A2D 3.1.0 C', ' ', 'A2D 3.1.0 C']
A2D 3.1.0.C represents the range [0 - 10], not [139 - 150]