0

Hello i am using python 3.4

I am trying to read a SQL-file (test2.sql) and write each line to another file (test1.sql), replacing all occurrences of a string.

The code i have below works fine when writing to .txt-files, but when trying to write to .sql-files strange Chinese characters trail each line

import fileinput
import sys

g = open('test1.sql', mode='w')
with fileinput.input(files=("test2.sql")) as f:
    for line in f:
        g.write(line.replace("database1","database2"))
2
  • Where do you see these strange characters? Are you opening the same file and just writing to a different file? Commented Oct 1, 2014 at 10:23
  • on the new file (test.1) where i expect a new line to be i get characters ਍ഀ *apolgies confused read and write file Commented Oct 1, 2014 at 15:01

1 Answer 1

1

You cannot meaningfully manipulate strings in a database as if it were a plain-text file.

You need to use the database native access method to ensure that the meta-data in the database is consistent. If you do otherwise, you are nearly guaranteed to corrupt database structures.

I'm a bit surprised this worked at all. It is likely that the next database modification (create, remove, update, delete) would hopelessly corrupt the database.

Sign up to request clarification or add additional context in comments.

2 Comments

i am not writing to a database, all i want to do is replace strings in a sql file without having strange characters for line endings when am viewing it using notepad
If by "sql file" you mean "SQL commands in a plain text file" then the strange characters are likely encoding problems. See docs.python.org/2/howto/unicode.html for annoyingly complex details. joelonsoftware.com/articles/Unicode.html would also help. I don't know if Notepad.exe allows you to chose an encoding, but (free) Notepad++ does.

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.