Issue
In my code i am using pygame and i am reading text files into maps. I am trying to create a long map that randomly joins my map segment text files together in a horizontal way to create a long map. How would i join multiple text files together and write the result to a new file.
Lets say text file 1 is equal to the below:
1111111111
100000000
100000000
1111111111
Lets say text file 2 is equal to the below:
1111111111
1000011111
1000000000
1111111111
And the result could look like this:
11111111111111111111
1000000001000011111
1000000001000000000
11111111111111111111
Thanks for the help and if anyone would like to check out my full project it is here
Solution
There are plenty of ways to do this. Here's another way:
filenames = (r"map1.txt", r"map2.txt")
# Each line from every file will be stored in a list as strings
lines = []
for filename in filenames:
with open(filename) as f:
for line_num, line in enumerate(f):
# You cannot index into a list if it doesn't exist, so
# you need to append to it first
if line_num == len(lines):
lines.append(line.strip())
else:
lines[line_num] += line.strip()
# This transforms the list into a single string, with a newline between every item
map_str = "\n".join(line for line in lines)
print(map_str)
Output:
11111111111111111111
1000000001000011111
1000000001000000000
11111111111111111111
By the way, are you sure you don't need each row of the map to be the same length? Some are 10 while others are 9.
Answered By - GordonAitchJay Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.