如何使用python从txt文件中读取特定数据

如何使用python从txt文件中读取特定数据,python,python-2.7,Python,Python 2.7,帮帮我,我有一个data.txt文件。我想读取文件112652447744中的特定数据,即目录C中的自由空间数据。 这是my data.txt文件的内容: Caption FreeSpace Size C: 112652447744 146776518656 D: 295803727872 299962986496 E: Z:

帮帮我,我有一个data.txt文件。我想读取文件
112652447744
中的特定数据,即目录C中的自由空间数据。 这是my data.txt文件的内容:

  Caption  FreeSpace     Size          
   C:      112652447744  146776518656  
   D:      295803727872  299962986496  
   E:                                   
   Z:                                   
您可以读取每一行(忽略第一行)并用空格分隔以获得每一列。这样可以提取每个分区的大小和可用空间:

contents = # here go the file contents
# split the text file into lines and ignore the first line
lines = contents.splitlines()[1:]
part_data = {}
for line in lines:
    columns = line.split()  # split the lines along the white space characters
    if len(columns) != 3:
        continue  # incomplete lines
    part_data[columns[0]] = (columns[1], columns[2])
这将为字典中的每个分区提供可用空间和大小。要获得实际结果,需要:

part_data['C:'][0]
如果只需要第二列和第二行,而忽略驱动器号,则可以将其缩减为以下内容:

contents = # here go the file contents
second_line = contents.splitlines()[1]
second_column = second_line.split()[1]
好了,但这要求它的格式始终相同。如果第二行没有三列,那么它实际上不会工作,很可能会导致索引器出现

请注意,
a_string.split()
会自动删除所有空白,而
a_string.split(“”)
也会返回其中的空白。请尝试以下操作:

#Open file in lines
file = open('path/to/txt','r').readlines()
#For each line
for disk in file:
    fields = disk.split("\t")
    #To check the total fields...
    if(len(fields)>1):

        print fields[1]

您的问题没有这样说,但是我可以假设您想要“查找”标题为C:的行中表示自由空间的值吗

除非您需要文件中的数据用于其他用途,否则只需逐行读取文件中的数据,直到得到结果。第一行是标题行,您可以使用“caption_header”和“fs_header”的位置来解析每个后续数据行

在您的示例中,这意味着我们要测试每行的第一个值是否包含C:,如果是,我们要寻找的答案将在第二列中。如果我们找到了答案,那么就没有必要搜索其余的行

def find_value(caption_header, fs_header, caption_value, fp):
    fs = None
    with open(fp) as fid:
        headers = fid.readline().strip().split()
        for i, h in enumerate(headers):
            if h == caption_header:
                caption_position = i
            if h == fs_header:
                fs_position = i
        line = fid.readline()
        while line != '':
            values = line.strip().split()
            if values[caption_position] == caption_value:
                fs = values[fs_position]
                break
    return fs
然后像这样使用它:

fs = find_value('Caption', 'FreeSpace', 'C:')

从文件中读取所有数据并仅从读取列表中提取所需的数据可能是一种解决方案吗?您是否已经尝试过任何方法?您希望它是动态的还是始终位于第二行的第二列?@xZise始终位于第二行的第二列如何读取file.txt
file=open('D:\Disk\u 2016-10-13.txt','r')contents=file.readlines()print contensts
当我运行时,我得到这个
['\xff\xfeC\x00a\x00p\x00t\x00i\x00o\x00n\x00\x00\x00F\x00r\x00e\x00e\x00e\x00S\x00c\x00e\x00\x00\x00\x00\x00i\x00z\]您首先需要解码的内容。文本似乎被编码为UTF-16,因此首先对其进行解码是有帮助的:
contents=file.read()
,然后是
contents=contents.decode(“UTF16”)
。您不需要使用
readlines()
,因为
splitlines()
也会这样做。使用
splitlines()
将在解码后对其进行拆分。