I have a file with data like this
01000000000
00000010000
...
00000100000
10000000000
I want to convert it to
0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
...
0 0 0 0 0 1 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0
How should I do it?
Thanks
CodePudding user response:
This snippet does it.
with open("path.txt", 'r') as file:
lines = file.readlines()
arr = []
for line in lines:
arr.append(' '.join(line.strip()) "\n")
print(arr)
with open("path.txt", 'w') as file:
file.writelines(arr)
CodePudding user response:
Read each line from the file removing any trailing whitespace. Use ' '.join() to intersperse spaces between each character. Save all the lines in a list.
Open the file for writing and output all lines from the list.
FILENAME = 'path.txt'
with open(FILENAME) as data:
outlines = [' '.join(line) for line in map(str.rstrip, data)]
with open(FILENAME, 'w') as data:
print(*outlines, sep='\n', file=data)