How to convert string "Серия 1" to string "\x412\x437\x440\x44b\x432\x430\x44f" for write to file.
def create_playlist(playlist):
gplaylist = "[playlist]\n"
playlist1 = json.loads(playlist)
x = 1;
for i in enumerate(playlist1):
for j in enumerate(i[1]['folder']):
gplaylist += "File" + str(x) + "=" + parse_file(j[1]['file']) + "\n"
# Variable: j[1]['title'] must converted to "\x412\x437\x440\x44b\x432\x430\x44f"
gplaylist += "Title" + str(x) + "=" + j[1]['title'] + "\n"
x += 1
gplaylist += "NumberOfEntries=" + str(x-1)
write_playlist(gplaylist)
def write_playlist(playlist):
with io.open('play_list.pls', 'w', encoding='utf-8') as outfile:
outfile.write(to_unicode(playlist))
You should stop playing with encodings where it's not really necessary. Everything works perfectly as it is:
$ python
>>> with open('part1.txt', 'w') as fout :
... fout.write( 'Серия 1\n' )
...
>>>
$ cat part1.txt
Серия 1
$
Related
I have a variable, first_line which is in the format of 1888,60,-32, and I want to separate this, for example, to equal x = 1888 y = 60 and z = -32, but they might be different lengths, eg, another one is 768,60,-13776.
I have tried this and it didn't allow me to split up the text into variables.
write.py
# open current file and read first line
with open(currentfile) as f:
first_line = f.readline()
first_line = first_line.rstrip()
print(currentfile)
print(first_line)
# define fullnamejson as END + first_line + .json
fullnamejson = "END_" + first_line + ".json"
# define fullname as END + first_line
fullname = "END_" + first_line
os.rename(currentfile, fullnamejson)
print(fullnamejson)
# define x y and z
x = "some value x"
y = "some value y"
z = "some value z"
# define formatted as what will be written to the file
formatted = "{\n \"id\": \"" + fullname + "\",\n \"name\": \"END\",\n \"icon\": \"waypoint-normal.png\",\n \"x\": " + x + ",\n \"y\": " + y + ",\n \"z\": " + z + ",\n}"
print(formatted)
# write to file
with open(fullnamejson, "w") as text_file:
##print(f(fullnamejson), file=text_file)
print(f'{formatted}', file=text_file)
zzz_split_1.txt (input)
1888,60,-32
fullnamejson (output)
{
"id": "END_1888,60,-32",
"name": "END",
"icon": "waypoint-normal.png",
"x": some value x,
"y": some value y,
"z": some value z,
}
Are you looking for this?
coords = first_line.split(",")
x, y, z = int(coords[0]), int(coords[1]), int(coords[2])
You were close, all you needed was to use split to divide the content!
f=open("a.txt", "r")
if f.mode == 'r':
contents =f.read()
f.close()
arr = contents.split(",")
fullnamejson = "END_" + contents + ".json"
print(fullnamejson)
fullname = "END_" + contents
formatted = "{\n \"id\": \"" + fullname + "\",\n \"name\": \"END\",\n \"icon\": \"waypoint-normal.png\",\n \"x\": " + contents[0] + ",\n \"y\": " + contents[1] + ",\n \"z\": " + contents[2] + ",\n}"
print(formatted)
with open(fullnamejson, "w") as text_file:
print(f'{formatted}', file=text_file)
1.You can split strings using function split.
2. You can assign result of expression that is a collection to more than one variable.
All written above looks like that in code:
x, y, z =your_string.split(',')
Just change quotation marks.(writing from iphone)
dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
the program keep giving me syntax error when I run it.
import re
import sys
import os
import time
from sys import argv
import xmltodict
if len(sys.argv) < 3:
message = '\n Get protein file in the form of pdf file from pdb website. \n\n Usage: '+sys.argv[0] + ' [4-letter PDBid] [resid range] \n' + ' Example: ' + sys.argv[0] + ' 2rh1 53-71\n' + ' Output File: pdb2rh1_res53-71.pdb'
print (message)
exit()
pdbID=sys.argv[1]
residRange=sys.argv[2]
residData=residRange.split('-')
residMin=int(residData[0])
residMax=int(residData[1])
twoletter=pdbID[1:3]
xmlfile=pdbID + '.xml'
pdbgzfile=pdbID + '.pdb.gz'
pdbFile=pdbID+'.pdb'
dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
wgetcom='wget https://files.rcsb.org/view/'+pdbFile+' -O '+pdbFile
print(wgetcom)
os.system(wgetcom)
f = open (pdbFile,'r')
k = 0
rc = 0
data = f.readlines()
g = open (dump.pdb, 'w')
for linedata in data:
line=linedata.strip()
words = line.split()
if(words[0] == 'ATOM'):
k=k+1
words[5]=int(line[22:26].strip())
if(words[5] in range(residMin,residMax+1)):
g.write(linedata)
for i in words:
if(i=='CA'):
rc = rc+1
print(rc)
the code is not working because it is giving me a syntax error for line number 22 that states dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' residMax + '.pdb'. so can you please help me with that?
Thanks so much on advance!
You've forgotten to add a + sign.
This line should work: dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' + residMax + '.pdb'
There must be a + sign between '_' and residMax as this is the Python concatenating strings syntax.
I have the following code:
def get_asset_info(asset_list):
import datetime
today = datetime.datetime.today()
day = today.strftime("%d")
for i in range( len( asset_list )):
raw_info = get_OHLC( asset_list[i], 15, get_server_time() )
info = raw_info['result'][asset_list[i]]
head = "time,open,high,low,close,vwap,volume,count"
formatted_info = ""
for i in range(len(info[0])):
formatted_info = formatted_info + info[0][i] + ","
file = open(asset_list[i]+"_"+day, "a")
file.write(head + "\n")
file.write(formatted_info)
file.close()
It is supposed to get some values, convert it into a string and write it to a file, dynamically generated.
It's not working like this and all the values are put in the same file.
If I change the last part of the code like the following, the files are generated:
formatted_info = str(info[0][0]) + "," + str(info[0][1]) + "," + str(info[0][2]) + "," + str(info[0][3]) + "," + str(info[0][4]) + "," + str(info[0][5]) + "," + str(info[0][6]) + "," + str(info[0][7])
file = open(asset_list[i]+"_"+day, "a")
file.write(head + "\n")
file.write(formatted_info)
file.close()
So the problem, as I can see, is in the for loop I create to generate my string, but there's no sense since the code that generates the file is not in the same loop.
Any ideas?
for i in range( len( asset_list )):
...
for i in range(len(info[0])):
...
# now what do you think i is now?
file = open(asset_list[i]+"_"+day, "a")
Changing second i to j should do the trick:
for i in range( len( asset_list )):
...
for j in range(len(info[0])):
formatted_info = formatted_info + info[0][j] + ","
file = open(asset_list[i]+"_"+day, "a")
or even better:
for i in range( len( asset_list )):
...
for piece in info[0]:
formatted_info = formatted_info + str(piece) + ","
file = open(asset_list[i]+"_"+day, "a")
or finally better:
for i in range( len( asset_list )):
...
formatted_info = ','.join(str(obj) for obj in info[0]) + ','
file = open(asset_list[i]+"_"+day, "a")
Could I please get some help on the following problem. I can't seem to spot where I have gone wrong in my code. I have 2 output csv files from my code. The first produces the right format but the second does not:
First output file (fileB in my code)
A,B,C
D,E,F
Second output file (fileC in my code)
A,B,
C
D,E,
F
Here is my code:
file1 = open ('fileA.csv', 'rt', newline = '')
shore_upstream = open('fileB.csv', 'wt', newline = '')
shore_downstream = open('fileC.csv', 'wt', newline = '')
for line in file1:
first_comma = line.find(',')
second_comma = line.find(',', first_comma + 1)
start_coordinate = line [first_comma +1 : second_comma]
start_coordinate_number = int(start_coordinate)
end_coordinte = line [second_comma +1 :]
end_coordinate_number = int (end_coordinte)
upstream_start = start_coordinate_number - 2000
downstream_end = end_coordinate_number + 2000
upstream_start_string = str(upstream_start)
downstring_end_string = str(downstream_end)
upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + start_coordinate
shore_upstream.write(upstream_shore + '\n')
downstream_shore = line[:first_comma]+ ','+ end_coordinte + ',' + downstring_end_string
shore_downstream.write(downstream_shore + '\n')
file1.close()
shore_upstream.close()
shore_downstream.close()
By the way, I am using python 3.3.
Your variable end_coordinte may contain non-decimal characters in it, and probably contains a \n\t at the end, resulting in that output.
The simplest solution might be to evaluate those strings as a number, and printing them back as strings.
Replace:
upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + start_coordinate
downstream_shore = line[:first_comma]+ ','+ end_coordinte + ',' + downstring_end_string
by:
upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + str(start_coordinate_number)
downstream_shore = line[:first_comma]+ ','+ str(end_coordinate_number) + ',' + downstring_end_string
And pay attention to the line[:first_comma] output, as it may also contain characters you are not expecting.
I'm having trouble using python to write strings into a file:
(what I'm trying to do is using python to generate some C programs)
The code I have is the following:
filename = "test.txt"
i = 0
string = "image"
tempstr = ""
average1 = "average"
average2 = "average*average"
output = ""
FILE = open(filename,"w")
while i < 20:
j = 0
output = "square_sum = square_sum + "
while j < 20:
tempstr = string + "_" + str(i) + "_" + str(j)
output = output + tempstr + "*" + tempstr + " + " + average2 + " - 2*" + average1 + "*" + tempstr
if j != 19:
output = output + " + "
if j == 19:
output = output + ";"
j = j + 1
output = output + "\n"
i = i + 1
print(output)
FILE.writelines(output)
FILE.close
The print gives me correct output, but the FILE has last line missing and some of the second last line missing. What's the problem in writing strings into file?
Thank you!
Probably help if you called the method...
FILE.close()
The problem is that you aren't calling the close() method, just mentioning it in the last line. You need parens to invoke a function.
Python's with statement can make that unnecessary though:
with open(filename,"w") as the_file:
while i < 20:
j = 0
output = "square_sum = square_sum + "
...
print(output)
the_file.writelines(output)
When the with clause is exited, the_file will be closed automatically.
Try:
with open(filename,"w") as FILE:
while i < 20:
# rest of your code with proper indent...
no close needed...
First, a Pythonified version of your code:
img = 'image_{i}_{j}'
avg = 'average'
clause = '{img}*{img} + {avg}*{avg} - 2*{avg}*{img}'.format(img=img, avg=avg)
clauses = (clause.format(i=i, j=j) for i in xrange(20) for j in xrange(20))
joinstr = '\n + '
output = 'square_sum = {};'.format(joinstr.join(clauses))
fname = 'output.c'
with open(fname, 'w') as outf:
print output
outf.write(output)
Second, it looks like you are hoping to speed up your C code by fanatical inlining. I very much doubt the speed gains will justify your efforts over something like
maxi = 20;
maxj = 20;
sum = 0;
sqsum = 0;
for(i=0; i<maxi; i++)
for(j=0; j<maxj; j++) {
t = image[i][j];
sum += t;
sqsum += t*t;
}
square_sum = sqsum + maxi*maxj*average*average - 2*sum*average;
Looks like your indentation may be incorrect, but just some other comments about your code:
writelines() writes the content of a list or iterator to the file.
Since your outputting a single string, just use write().
lines ["lineone\n", "line two\n"]
f = open("myfile.txt", "w")
f.writelines(lines)
f.close()
Or just:
output = "big long string\nOf something important\n"
f = open("myfile.txt", "w")
f.write(output)
f.close()
As another side note it maybe helpful to use the += operator.
output += "more text"
# is equivalent to
output = output + "more text"