这是一个非常基本的问题,但是在Visual Studio中,我想将一堆名称转换为字符串数组。对于100多个名称,我将如何快速做到?
当前我的py文件:
Owen
Dylan
Luke
Gabriel
Anthony
Isaac
Grayson
Jack
Julian
Levi
我希望它看起来像什么
["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
]
答案 0 :(得分:0)
您可以打开文件并轻松读取其所有行:
with open('names_file.txt', 'r') as fp:
names = fp.readlines()
print(names)
在read mode
中打开文本文件并读取所有行,每一行将是names
列表中的一项。
答案 1 :(得分:0)
只需打开文件并将其分配给数组变量
with open('names_file.txt', 'r') as fp:
names = fp.read().splitlines() #splitlines removes /n from each array element
print(names)
以r
模式打开文件,并将字符串中的每一行分配给变量name
答案 2 :(得分:0)
如果在与您提供的示例相同的文件中将名称列表转换为Python列表,则可以尝试以下操作:
names = []
with open('names.py', 'r') as inFile:
names = [name for name in inFile]
with open('names.py', 'w') as outFile:
outFile.write('[')
for name in names:
finalName = "\"" + name + "\""
outFile.write(finalName.replace('\n','') + ',\n')
outFile.write(']')
输出:
["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
]
请注意,由于最后一个逗号,以上内容不是有效的Python列表。如果要创建有效列表,可以使用以下内容:
names = []
with open('names.py', 'r') as inFile:
names = [name for name in inFile]
with open('names.py', 'w') as outFile:
newNames = ["".join(["\"",name,"\""]).replace("\n","") for name in names]
outFile.write('[')
outFile.write(",\n".join(newNames))
outFile.write(']')
输出:
["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi"]