How to remove quotation marks from variable that writes to a file? - python

Everytime i run this part code everything goes smoothly BUT when it writes the variable to the file it shows up with quotation marks, is there a way to remove them and write it as simple text?
try:
with open(tokens) as f:
lines = f.readlines()
answer = random.choice(lines)
print(answer)
except:
file_name = tokens
opened_file = open(tokens, 'a')
opened_file.write("%r\n" %user_input)
opened_file.close()
writing in the file looks like this:
'Whats up'
and i want it to look like this:
Whats up

In your line that writes to the log you are using %r as your format in the string. the Python docs say
Replacing %s and %r:
>
"repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"
So replace this line
opened_file.write("%r\n" %user_input)
with
opened_file.write("%s\n" %user_input)

Related

How to create a program that writes a print("hello world"), in the main file where the original program was written?

If I want to run a program that writes a print("hello world") in the code of my main file, where I wrote the original program, how would I do that in Python?
I thought something like:
import main
with open("main.py " , "a+") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data)>0:
file_object.write("\n")
file_object.write('print("hello world)')
but the console shows this:
ValueError: I/O operation on closed file.
From my understanding, you are trying to determine if a file has content and if it does include a new line, and then append the print statement.
You do not need to use seek you can just check the size of the file:
import os
if os.path.getsize(filename):
# file isn't empty
else:
# file is empty
You should also close the quotation marks in your print statement
You can use __file__ which gives you the path of your file and then append your text to it.
path = __file__
f = open(path, "a")
f.write('\nprint("hello world")')
f.close()
you wrong because Indent correctly, like this. You can modify like:
import main
with open("main.py" , "a+") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data)>0:
file_object.write("\n")
file_object.write('print("hello world")')

trying to print human readable ascii string

I am trying to print a string which is human readable ascii but not getting any output. What am i missing?
import string
file = open("file.txt", "r")
data = file.read()
data = data.split("\n")
for line in data:
if line not in string.printable:
continue
else:
print line
If your file's content is text, you should read files like this:
import string
with open("file.txt", "r") as file:
for line in file:
if all( c in string.printable for c in line):
print line
You must check every character individually to see if it is printable. There is another post about checking that string is printable: Test if a python string is printable
Also, you can read about context manager about how to open file right way: What is the most pythonic way to open a file?

Some issue with Unicode encoding

I am trying to open and parse a Json file using python script and write its content into another Json file after formatting it as I want. Now my source Json file has character /"
which I want to replace with a blank. I don't have any issue in parsing or creating news file only the issue is that character is not getting replaced by blank. How do I do it. Earlier I have achieved the same task but then there was no such character in the document that time.
Here is my code
doubleQuote = "\""
try:
destination = open("TodaysHtScrapedItemsOutput.json","w") # open JSON file for output
except IOError:
pass
with open('TodaysHtScrapedItems.json') as f: #load json file
data = json.load(f)
print "file successfully loaded"
for dataobj in data:
for news in data[cnt]["body"]:
news = news.encode("utf-8")
if(news.find(doubleQuote) != -1): # if doublequotes found in first body tag
# print "found double quote"
news.replace(doubleQuote,"")
if(news !=""):
my_news = my_news +" "+ news
destination.write("{\"body\":"+ "\""+my_news+"\"}"+"\n")
my_news = ""
cnt= cnt + 1
Some things to try:
You should write and read the json files as binaries, so "w" becomes "wb" and you need to add "rb".
You can define your search string as unicode, with:
doubleQuote = u'"'
You can lookup the integer value of the character with this command.
ord(u'"')
I get 34 as a response. The reverse function is chr(34). Are the double quotes you are looking for the same double quotes as the json contains? See here for details.
You don't need the if loop to check if news contains the '"'. Doing a replace on 'news' is enough.
Try these steps and let me know if it still doesn't work.
str.replace doesn't change the original string.So you need to assign the string back to news.
if(news.find(doubleQuote) != -1): # if doublequotes found in first body tag
# print "found double quote"
news = news.replace(doubleQuote,"")

Python writing to file using stdout and fileinput

I have the following code, which modifies each line of the file test.tex by making a regular expression substitution.
import re
import fileinput
regex=re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
for line in fileinput.input('test.tex',inplace=1):
print regex.sub(r'\3\2\1\4\5',line),
The only problem is that I only want the substitution to apply to certain lines in the file, and there's no way to define a pattern to select the correct lines. So, I want to display each line and prompt the user at the command line, asking whether to make the substitution at the current line. If the user enters "y", the substitution is made. If the user simply enters nothing, the substitution is not made.
The problem, of course, is that by using the code inplace=1 I've effectively redirected stdout to the opened file. So there's no way to show output (e.g. asking whether to make the substitution) to the command line that doesn't get sent to the file.
Any ideas?
The file input module is really for dealing with more than one input file.
You can use the regular open() function instead.
Something like this should work.
By reading the file then resetting the pointer with seek(), we can override the file instead of appending to the end, and so edit the file in-place
import re
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
with open('test.tex', 'r+') as f:
old = f.readlines() # Pull the file contents to a list
f.seek(0) # Jump to start, so we overwrite instead of appending
for line in old:
s = raw_input(line)
if s == 'y':
f.write(regex.sub(r'\3\2\1\4\5',line))
else:
f.write(line)
http://docs.python.org/tutorial/inputoutput.html
Based on the help everyone provided, here's what I ended up going with:
#!/usr/bin/python
import re
import sys
import os
# regular expression
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
# name of input and output files
if len(sys.argv)==1:
print 'No file specified. Exiting.'
sys.exit()
ifilename = sys.argv[1]
ofilename = ifilename+'.MODIFIED'
# read input file
ifile = open(ifilename)
lines = ifile.readlines()
ofile = open(ofilename,'w')
# prompt to make substitutions wherever a regex match occurs
for line in lines:
match = regex.search(line)
if match is not None:
print ''
print '***CANDIDATE FOR SUBSTITUTION***'
print '--: '+line,
print '++: '+regex.sub(r'\3\2\1\4\5',line),
print '********************************'
input = raw_input('Make subsitution (enter y for yes)? ')
if input == 'y':
ofile.write(regex.sub(r'\3\2\1\4\5',line))
else:
ofile.write(line)
else:
ofile.write(line)
# replace original file with modified file
os.remove(ifilename)
os.rename(ofilename, ifilename)
Thanks a lot!

Reading lines including space

I want to read file including spaces in each lines
My current code
def data():
f = open("save.aln")
for line in f.readlines():
print "</br>"
print line
I am using python and output embedded in html
File to be read - http://pastebin.com/EaeKsyvg
Thanks
It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets
def data():
print "<pre>"
f = open("save.aln")
for line in f.readlines():
print line
print "</pre>"
Note that in this case you don't need the <br> elements either, since the newline characters are also preserved.
The problem that you are faced with is that HTML ignores multiple whitespaces. #itsadok's solution is great. I upvoted it. But, it's not the only way to do this either.
If you want to explicitly turn those whitespaces into HTML whitespace characters, you could to this:
def data():
f = open("save.aln")
for line in f.readlines():
print "<br />"
print line.replace(" ", "&nbsp")
Cheers
import cgi
with open('save.aln') as f:
for line in f:
print cgi.escape(line) # escape <, >, &
print '<br/>'

Categories

Resources