-1

this is a pretty basic question but inside Visual Studio I would like to convert a bunch of names into an array of strings. How would I quickly do that for 100+ names?

My py file currently:

Owen
Dylan
Luke
Gabriel
Anthony
Isaac
Grayson
Jack
Julian
Levi

What I want it to look like:

["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
]
zamir
  • 2,144
  • 1
  • 11
  • 23
Turtle
  • 49
  • 1
  • 7

3 Answers3

0

You can open a file and read all its lines pretty easily:

with open('names_file.txt', 'r') as fp:
    names = fp.readlines()

print(names)

Open the text file in read mode and read all the lines, each line will be an item in names List.

blakev
  • 4,154
  • 2
  • 32
  • 52
0

Just open the file and assign it to an array variable

with open('names_file.txt', 'r') as fp:
names = fp.read().splitlines()  #splitlines removes /n from each array element
print(names)

open the file in r mode and assign each line in the string to variable name

0

If converting a list of names to a Python list in the same file as in the example you provided, you could try the following:

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(']')

Output:

["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi",
]

Note that the above is not a valid Python list due to the last comma. If you want to make a valid list, you can use the following:

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(']')

Output:

["Owen",
"Dylan",
"Luke",
"Gabriel",
"Anthony",
"Isaac",
"Grayson",
"Jack",
"Julian",
"Levi"]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29