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)
Related
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
$
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")
I'm relatively new to python and was wondering if I could get some assistance in parsing data so that it is easier to analyze.
My data is in the following form (each is an entire line):
20160930-07:06:54.481737|I|MTP_4|CL:BF K7-M7-N7 Restrict for maxAggressive: -4.237195
20160930-07:06:54.481738|I|MTP_4|CL:BF K7-M7-N7 BidPrice: -5.0 mktBestBid: -5.0 bidTheo: -4.096774 bidSeedEdge: 0.195028 bidUnseedEdge: CL:BF K7-M7-N7 = 0.14042 Min Bid: -6.0 Max Ticks Offset: 1 Max Aggressive Ticks: 1
This is my code so far
# Output file
output_filename = os.path.normpath("Mypath/testList.log")
# Overwrites the file
with open(output_filename, "w") as out_file:
out_file.write("")
# Open output file
with open(output_filename, "a") as out_file:
# Open input file in 'read' mode
with open("mypath/tradedata.log", "r") as in_file:
# Loop over each log line, Grabs lines with necessary data
for line in islice(in_file, 177004, 8349710):
out_file.write(line)
Would it be easiest to just go through and do it by keywords like; bidUnseedEdge, mktBesdBid, etc. ?
infilename = "path/data.log"
outfilename = "path/OutputData.csv"
with open(infilename, 'r') as infile,\
open(outfilename, "w") as outfile:
lineCounter = 0
for line in infile:
lineCounter += 1
if lineCounter % 1000000 == 0:
print lineCounter
data = line.split("|")
if len(data) < 4:
continue
bidsplit = data[3].split("bidTheo:")
namebid = data[3].split("BidPrice:")
if len(bidsplit) == 2:
bid = float(bidsplit[1].strip().split()[0])
bidname = namebid[0].strip().split(",")[0]
#print "bidTheo," + data[0] + "," + str(bid)
outfile.write("bidTheo," + data[0] + "," + bidname + "," + str(bid) + "\n")
offersplit = data[3].split("offerTheo:")
nameoffer = data[3].split("AskPrice:")
if len(offersplit) == 2:
offer = float(offersplit[1].strip().split()[0])
offername = nameoffer[0].strip().split(",")[0]
#print "offerTheo," + data[0] + "," + str(offer)
outfile.write("offerTheo," + data[0] + "," + offername + "," + str(offer) + "\n")
print "Done"
I have the following code which creates the txt file I require from a shp.file with the data I need. I have a folder called profiles containing a few number of shape files named (profil1.shp, profil2.shp, profil3.shp etc.). I was wondering how to create a loop so that the script creates for each file a txt file with the same name (eg. for profil1.shp create profil1.txt, profil2.shp create profil2.txt and so on).
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
edit: the code is returning a Could not open file.Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.
import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
You can use os.listdir() to list the files and folders in the current directory.
This returns a list of all files in the current directory (or the directory given to it as parameter , if no parameter is specified it checks the current directory) .
Then you can check for files with the name ending with .shp using string.endswith() function and then use that to create your new files.
Example of a small portion -
import os , os.path
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
At the end s1 would contain the file with extension as .txt .
Then you can do your logic on this file, and keep on doing like this.
Full code would look something like -
import ogr, os, sys, osr,os.path
os.chdir('..\profiles')
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
A better way of openning files, etc is using with statement. Look up its tutorial here.
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"