I am reading a file like this:
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path 'detections/')
landmarks = os.listdir(path 'landmarks/')
for file in detections:
with open(path 'detections/' file, 'r') as f:
print(f.read())
This is the output:
128.0 96.0
191.0 96.0
182.0 136.0
138.0 181.0
186.0 180.0
How can I replace the linebreaks with spaces in every single such file? I want the file to look like this:
128.0 96.0 191.0 96.0 182.0 136.0 138.0 181.0 186.0 180.0
I know I can use str.replace('\n', ' ')
but how can I actually edit the contents of the file line by line?
CodePudding user response:
You can still use replace
, but you need to f.write
after:
# Open and over-write (r )
with open("file.txt", 'r ') as f:
x = f.read()
x = x.replace("\n", " ")
f.seek(0)
f.write(x)
CodePudding user response:
Usually you don't edit a file in-place: you read it and write elsewhere. You can then replace the input file with the output once you've succeeded.
with open('input.txt', 'rt') as fi, open('output.txt', 'wt') as fo:
for line in fi:
fo.write(line.replace('\n', ' '))
# optionally move output.txt to input.txt afterward
That being said, for small files and toy examples, you can read in the whole thing and then write it back under the same name:
with open('input.txt', 'rt') as f:
data = f.read()
with open('input.txt', 'wt') as f:
f.write(data.replace('\n', ' '))
CodePudding user response:
You can consider using regex:
import re
path = '/home/onur/Deep3dPortrait/examples/'
detections = os.listdir(path 'detections/')
landmarks = os.listdir(path 'landmarks/')
for file in detections:
with open(path 'detections/' file, 'w') as f:
f.write(re.sub("\n", " ", f.read()))