I have written a code where I want my data to file exactly as it is but padding spaces.
No delimiter should be there in file.
Data need to be read from this file, A.txt
:
a;j;kk
gh;jsk;kk;
gsh;kks;jj
Expected output in file:
a j kk
gh jsk kk
gsh kks jj
My main motive is to get data with padding in file and should not have any delimiter or single quote.
My code:
import csv as cv
md=''
with open(r'C:\\Desktop\\A.txt',mode='r') as file:
csvFile = cv.reader(file)
for i in csvFile:
md = md (i[0].rjust(10))
md = md (i[1].rjust(10))
md = md (i[2].rjust(10))
result = md
with open(r'C:\\Desktop\\B.txt',mode='w') as file:
cw = cv.writer(file)
cw.writerow(result)
md =''
result=''
CodePudding user response:
You can use print
and f-strings
to get the expected result:
import csv
with (open('A.txt', 'r') as fpa,
open('B.txt', 'w') as fpb):
reader = csv.reader(fpa, delimiter=';')
for row in reader:
print(' '*10, *[f'{val:10}' for val in row], sep='', file=fpb)
Output B.txt
:
a j kk
gh jsk kk
gsh kks jj