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
CodePudding user response:
This logic works when the number of lines in both files are same.
with open("file1") as file1, open("file2") as file2:
file1_lines= file1.readlines()
file2_lines = file2.readlines()
result = [line[0] line[1] for line in zip(file1_lines, file2_lines)]
with open("outfile", "w") as outfile:
outfile.write("\n".join(result))
CodePudding user response:
- Input files: x.txt, y.txt
- Output file: z.txt
Code
with open("x.txt") as xh, open('y.txt') as yh, open("z.txt","w") as zh:
for x, y in zip(xh, yh):
zh.write(x.rstrip() y)
CodePudding user response:
var1 = """
1111111111
100000000
100000000
1111111111
"""
var2 = """
1111111111
1000011111
1000000000
1111111111
"""
var1 = [x.strip() for x in var1.split("\n") if x]
var2 = [x.strip() for x in var2.split("\n") if x]
for x, y in zip(var1, var2):
print(f"{x}{y}")
CodePudding user response:
# Read files
f1 = open('file1.txt', 'r', encoding='utf-8')
f2 = open('file2.txt', 'r', encoding='utf-8')
# Read lines
lines1 = f1.readlines()
lines2 = f2.readlines()
# If len(file1) < len(file2) append file1 zeros and vice versa.
lines1.extend([0,] * (len(lines2) - len(lines1)))
lines2.extend([0,] * (len(lines1) - len(lines2)))
# remove \n from file1
lines1 = [x[:-2] for x in lines1]
# print result XD
print(''.join(list(map(lambda x: x[0] "{0:1}".format(x[1]), zip(lines1, lines2)))))
CodePudding user response:
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.