0

I am trying to save a text file in sqlite using python but when I try to retrieve the file, I see newline character and other characters. Is there any way to output the file as it is like the original file? Is there any work around.

import sqlite3

conn=sqlite3.connect('example.db')
c=conn.cursor()

c.execute("create table code_tag1 (language text, code BLOB, tag text)")
#c.execute("select * from sqlite_master")
with open("bubblesort_java.txt","rb") as f:
    ablob=f.read()

c.execute("insert into code_tag1 values('java',?,'bubblesort')",[buffer(ablob)])
conn.commit()
row=c.execute("select * from code_tag1").fetchone()
print (repr(str(row[1])))
conn.close()

The output is :

'import java.util.Scanner;\r\n \r\nclass BubbleSort {\r\n  public static void main(String []args)     
{\r\n    int n, c, d, swap;\r\n    Scanner in = new Scanner(System.in);\r\n \r\n     
System.out.println("Input number of integers to sort");\r\n    n = in.nextInt();\r\n \r\n    int 
array[] = new int[n];\r\n \r\n    System.out.println("Enter " + n + " integers");\r\n \r\n    for 
(c = 0; c < n; c++) \r\n      array[c] = in.nextInt();\r\n \r\n    for (c = 0; c < ( n - 1 ); 
c++) {\r\n      for (d = 0; d < n - c - 1; d++) {\r\n        if (array[d] > array[d+1]) /* For 
descending order use < */\r\n        {\r\n          swap       = array[d];\r\n          array[d]   
= array[d+1];\r\n          array[d+1] = swap;\r\n        }\r\n      }\r\n    }\r\n \r\n    
System.out.println("Sorted list of numbers");\r\n \r\n    for (c = 0; c < n; c++) \r\n      
System.out.println(array[c]);\r\n  }\r\n}'

How can I get the code as it is in original file?

Thanks

Abhinav

1
  • Have you tried removing the repr() on the print line? Commented Apr 8, 2014 at 18:32

1 Answer 1

3

There's nothing wrong with the output. You're printing the repr of the string, which is why it shows the \r, \n, etc.

>>> data = """Hello
... World"""
>>> 
>>> print data
Hello
World
>>> print repr(data)
'Hello\nWorld'
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks aneroid and rafael.. repr was the problem..I read it gives the object representation so included that.. now I got the actual meaning thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.