I have a text file:
a
aaa
aaa
a
my desired outcome is:
a N
aaa N
aaa N
a N
I wrote the following
newf=""
with open('testfile.txt','r') as f:
for line in f:
if len(line) < 87:
newf+=line.strip()+" "
else:
newf+=line.strip()+"Nn"
f.close()
with open(‘testfile.txt’,’w’) as f:
f.write(newf)
f.close()
When I run this my outcome becomes
a aaa aaa a
I can’t figure out why it changes the output to one line.
7
You can consider f-strings to help you do the formatting.
def reformat_file(filename, desired_length=87, suffix='N'):
lines = []
with open(filename, 'r') as fp:
for line in fp:
line = line.strip()
formatted = line
if len(line) < desired_length:
formatted = f"{line:{desired_length}}{suffix}"
lines.append(formatted)
with open(filename, 'w') as fp:
fp.write('n'.join(lines))
return
if __name__ == "__main__":
reformat_file("testfile.txt")
Running reformat_file
where testfile.txt
contains the below
a
aaa
aaa
a
a really long line that will have more than the threshold number of characters is written here.
abc
Will rewrite overwrite testfile.txt
with the following.
a N
aaa N
aaa N
a N
a really long line that will have more than the threshold number of characters is written here.
abc N
It’s changing it to one line because it is only seeing the following code which says just add a space between them.
newf+=line.strip()+" "
If you would like your desired outcome you would change the above to something like the following
newf+=line.strip()+"tttttNn"
adjust for how many tabs you would like for your desired spacing.
the easiest is just f-string
for line in f:
if len(line) < 87:
print(f'{line:<87}N')
else:
line = list(line)
line[87] = 'N'
print(''.join(line))