有什么方法可以改变由文件行组成的列表中的元素吗?

2024-09-27 09:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个写在文件中的书籍列表(每本书都是一行,它有多个属性除以,,最后一个属性是True或False),然后使用

list_of_books = open('books'.txt').read().split()

我必须把真改假,反之亦然, 有什么办法吗

列表示例

['qwe,rty,1999,1231231231234,Drama,1000,1,True',
 'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
 'tui,fgh,2009,4564564564567,Horror,900,5,True']

Tags: 文件oftxtfalsetrue列表read属性
2条回答
import csv
itertools

inverse ={"True":"False", "False":"True"}

with open('path/to/input') as infile, open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout)
    for *row,b in csv.reader(infile):
        outfile.write(itertools.chain(row, [inverse[b]]))

如果您知道布尔值总是在末尾,那么您可以简单地更改字符串的内容,如下所示:

exampleList = ['qwe,rty,1999,1231231231234,Drama,1000,1,True',
               'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
               'tui,fgh,2009,4564564564567,Horror,900,5,True']

#Change the second element in the list from True to False
listElement = exampleList[1]
exampleList[1] = listElement[:-4] + "False"

print(exampleList)

或者,可以使用split()来完成

exampleList = ['qwe,rty,1999,1231231231234,Drama,1000,1,True',
               'rty,asd,1900,2342342342345,Fantasy,1000,4,True', 
               'tui,fgh,2009,4564564564567,Horror,900,5,True']

listElement = exampleList[1].split(",")
listElement[-1] = "False"
exampleList[1] = listElement

print(exampleList)

相关问题 更多 >

    热门问题