Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write data to file without single quote?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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=''
     

>Solution :

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        
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading