I am trying to write a function that reads a file, and appends the lines of a file into a list. For example a file that reads:
hello
goodbye
should return the list:
[["h","e","l","l","o"]
["g","o","o","d","b","y","e"]]
I have created a helper function splitLine that takes as input, a string and would return a list of the letters in the string. For example "abc"
would become ["a","b","c"]
I am having trouble inserting new lines and stripping the "\\r" and "\\n" from the lists. Here is my code:
def createGrid(filename):
myFile = open(str(filename),"r")
myGrid = []
for line in myFile:
myLine = splitLine(line)
myGrid.append(myLine)
return myGrid
You can probably try iterate through multiple for loops like this
def createGrid(filename):
myFile = open(str(filename),"r")
myGrid = []
for line in myFile:
for apl in line:
myLine = apl.splitlines()
myGrid.append(myLine)
return myGrid
A lot of what you want to do is handled by built-in methods in Python.
Wrapping list()
around a string will split it into a list of characters; using the .strip()
method on a string will remove leading and trailing whitespaces (such as '\\r\\n'
); and you can loop through each row of a file you have opened using a for
loop.
def create_grid(filename):
with open(filename, 'r') as fp:
return [list(row.strip()) for row in fp]
Here is another solution:
def createGrid(filename):
myFile = open(str(filename),"r")
myGrid = []
for line in myFile:
myGrid.append(list(line.strip()))
return myGrid
print createGrid("input.txt")
output:
[['h', 'e', 'l', 'l', 'o'], ['g', 'o', 'o', 'd', 'b', 'y', 'e']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.