python:创建字符串列表
我有很多文件正在阅读。我想要一个包含文件内容的列表。我把整个内容读成一个字符串 我需要一个如下所示的列表:python:创建字符串列表,python,string,list,Python,String,List,我有很多文件正在阅读。我想要一个包含文件内容的列表。我把整个内容读成一个字符串 我需要一个如下所示的列表: ["Content of the first file", "content of the second file",...] 我尝试过各种方法,如追加、扩展或插入,但它们都希望列表作为参数,而不是str,因此我最终得到以下结果: [["Content of the first file"], ["content of the second file"],...] 如何获取包含字符串的
["Content of the first file", "content of the second file",...]
我尝试过各种方法,如追加
、扩展
或插入
,但它们都希望列表
作为参数,而不是str
,因此我最终得到以下结果:
[["Content of the first file"], ["content of the second file"],...]
如何获取包含字符串的列表,然后添加字符串,而不将其转换为列表列表
编辑
还有代码吗
for file in os.listdir("neg"):
with open("neg\\"+file,'r', encoding="utf-8") as f:
linesNeg.append(f.read().splitlines())
for file in os.listdir("pos"):
with open("pos\\"+file,'r', encoding="utf-8") as f:
linesPos.append(f.read().splitlines())
listTotal = linesNeg + linesPos
这肯定不止一种方法。假设您将打开的文件作为文件对象
f1
和f2
:
alist = []
alist.extend([f1.read(), f2.read()])
或
alist = [f.read() for f in (f1, f2)]
就我个人而言,我会这样做,但给这只猫剥皮的方法不止一种
file_names = ['foo.txt', 'bar.txt']
def get_string(file_name):
with open(file_name, 'r') as fh:
contents = fh.read()
return contents
strings = [get_string(f) for f in file_names]
append
应该可以工作。它需要任何东西,而不仅仅是一个列表。您有任何代码要显示吗?根据第二个输出(您正在获得),您正在执行的位置.append()
,使用.extend()
,在尝试附加到之前,请确保linesNeg和linesPos存在them@anonymousextend执行了技巧.append()
而不是.append[]
即[]
->()
这就是我正在做的,但是我得到的是列表列表,而不是字符串列表。当我打印listNeg或listTotal时,它们是字符串列表。@user3813234这是因为您正在进行拆分行
您想要[“内容文件1”,“内容文件2”]
还是[“文件1行1”,“文件1行2”,“文件2行1”]
@Patrick Haugh前者:[“整个内容文件1”,“整个内容文件2”…]@用户3813234则不使用splitline
。它接受一个字符串并使其成为一个字符串列表,这正是您不想要的
file_names = ['foo.txt', 'bar.txt']
def get_string(file_name):
with open(file_name, 'r') as fh:
contents = fh.read()
return contents
strings = [get_string(f) for f in file_names]