简体   繁体   English

读取文本文件中的行并将其转换为字符串列表

[英]Read and convert row in text file into list of string

I have a text file data.txt that contains 2 rows of text. 我有一个包含2行文本的文本文件data.txt

first_row_1    first_row_2    first_row_3
second_row_1    second_row_2    second_row_3

I would like to read the second row of the text file and convert the contents into a list of string in python. 我想读取文本文件的第二行,并将内容转换为python中的字符串列表。 The list should look like this; 列表应该如下所示;

txt_list_str=['second_row_1','second_row_2','second_row_3']

Here is my attempted code; 这是我尝试过的代码;

import csv
with open('data.txt', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)
    row2 = next(reader)

my_list = row2.split("  ")

I got the error AttributeError: 'list' object has no attribute 'split' 我得到了错误AttributeError: 'list' object has no attribute 'split'

I am using python v3. 我正在使用python v3。

EDIT: Thanks for all the answers. 编辑:谢谢你的所有答案。 I am sure all of them works. 我相信所有这些都有效。 But can someone tell me what is wrong with my own attempted code? 但有人可以告诉我自己尝试的代码有什么问题吗? Thanks. 谢谢。

The reason your code doesn't work is you are trying to use split on a list, but it is meant to be used on a string. 你的代码不起作用的原因是你试图在列表上使用split ,但它意味着在字符串上使用。 Therefore in your example you would use row2[0] to access the first element of the list. 因此,在您的示例中,您将使用row2[0]来访问列表的第一个元素。

my_list = row2[0].split("    ")

Alternatively, if you have access to the numpy library you can use loadtxt . 或者,如果您可以访问numpy库,则可以使用loadtxt

import numpy as np

f = np.loadtxt("data.txt", dtype=str, skiprows=1)

print (f)
# ['second_row_1' 'second_row_2' 'second_row_3']

The result of this is an array as opposed to a list. 结果是数组而不是列表。 You could simply cast the array to a list if you require a list 如果需要列表,可以简单地将数组转换为列表

print (list(f))
#['second_row_1', 'second_row_2', 'second_row_3']

Use read file method to open file. 使用read file方法打开文件。

Eg 例如

>>> fp = open('temp.txt')

Use file inbuilt generator to iterate lines by next method, and ignore first line. 使用文件内置生成器通过下一个方法迭代行,并忽略第一行。

>>> next(fp)
'first_row_1    first_row_2    first_row_3)\n'

Get second line in any variable. 在任何变量中获取第二行。

>>> second_line = next(fp)
>>> second_line
'second_row_1    second_row_2    second_row_3'

Use Split string method to get items in list. 使用拆分字符串方法获取列表中的项目。 split method take one or zero argument. split方法取一个或零参数。 if not given they split use white space for split. 如果没有给他们分开使用白色空间进行拆分。

>>> second_line.split()
['second_row_1', 'second_row_2', 'second_row_3']

And finally close the file. 最后关闭文件。

fp.close()

Note: There are number of way to get respective output. 注意:有多种方法可以获得相应的输出。 But you should attempt first as DavidG said in comment. 但是你应该首先尝试DavidG在评论中说。

with open("file.txt", "r") as f:
    next(f)    # skipping first line; will work without this too
    for line in f:
        txt_list_str = line.split()
print(txt_list_str)

Output 产量

['second_row_1', 'second_row_2', 'second_row_3']

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

相关问题 python中如何将字符串转换为列表,从文本文件中读取字符串 - How to convert a string to list in python, the string is read from a text file 如何读取文本文件并转换为列表以与 Python 中的统计包一起使用 - How to read a text file and convert into a list for use with statistics package in Python 读取文本文件以创建列表,然后转换为字典 python - Read text file to create list and then convert to dictionary python Python 3.6 - 从文件中读取编码文本并转换为字符串 - Python 3.6 - Read encoded text from file and convert to string 使用分隔符分隔行和列并将字符串转换为列表并计算文本文件中最后一列的总和,而不使用 pandas - Sseparate row and columns with delimiter and convert string into list and calculate sum of the last column from text file without using pandas 如何将包含列表列表的文本文件转换为字符串? - How do I convert a text file containing a list of lists to a string? 将列表中的整数转换为要写入文本文件并稍后检索的字符串 - Convert integer within a list into a string to be written to a text file and later retrieved 使用 Python 在文件中逐行将字符串转换为日期 - Convert String to Date row by row in a file with Python 读取文本文件以在python中列出 - Read text file to list in python 从文本文件中读取列表 - Read list from text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM