Posts
 
Reputation
Joined
Last Seen
Ranked #464
Strength to Increase Rep
+8
Strength to Decrease Rep
-2
95% Quality Score
Upvotes Received
26
Posts with Upvotes
23
Upvoting Members
16
Downvotes Received
1
Posts with Downvotes
1
Downvoting Members
1
13 Commented Posts
2 Endorsements
Ranked #621
Ranked #305
~114.33K People Reached
Favorite Forums
Favorite Tags

133 Posted Topics

Member Avatar for RMartins

[QUOTE=RMartins;537916]but how can i prove for example that the result of sqrt(n) is an integer?[/QUOTE] You can do this (maybe is there more elegant way) [CODE] if math.sqrt(n) == float(int(math.sqrt(n))): print "sqrt(n) is an integer" [/CODE]

Member Avatar for pythonBasic
0
726
Member Avatar for gishi

[CODE] import csv reader = csv.reader(open("c:\sample.dat")) d={} for row in reader: d[row[0]]=row[1:] [/CODE]

Member Avatar for Gribouillis
0
15K
Member Avatar for lionaneesh

Just a quick point. To turn an object into string, you can define the special method __repr__ in your object : [CODE] class myobject: def __init__(self, name): self.name=name def __repr__(self): return "my name is %s" % (self.name) o=myobject("toto") print o > toto [/CODE]

Member Avatar for mail2sanjay
1
875
Member Avatar for jcmeyer

I'd write [CODE] self.cursor.execute("INSERT INTO DatabaseName (C1, C2, C3, C4, C5) SELECT (C1, C2, C3, C4, C5) FROM DatabaseName WHERE C1='%s'", [newC1Value]) [/CODE]

Member Avatar for webstart
0
221
Member Avatar for sys73r

[QUOTE=sys73r;1691325]my bad, the code i got is: input.csv 1,2,text, date, qwertyuiopasdfghjklñzxcvbnm, yhnujmik,2121212121 [CODE]import csv reader = csv.reader(open('input.csv', 'rb'), delimiter=',',quoting=csv.QUOTE_NONNUMERIC)) csv_out = csv.writer(open('output.csv', 'w')) for row in reader: content = row[0] + row[1] + row[5] + row[6] csv_out.writerow( content )[/CODE] which is giving me: 1,2,y,h,n,u,j,m,i,k,2,1,2,1,2,1,2,1,2,1 instead of 1,2,yhnujmik,2121212121 thanks![/QUOTE] Ok with …

Member Avatar for sys73r
0
199
Member Avatar for david_wislon

This code goes recursively in all the sudirs of your rootdir. Open all the files, read the lines, calls a function to process your line (here, it does nothing) and overwrite your files with your new lines [code=python] import os rootdir='c:\Your\Path' def doWhatYouWant(line): return line for subdir, dirs, files in …

Member Avatar for paxton91
0
706
Member Avatar for flebber

Another method [CODE] import fnmatch pattern = '*.rtf' files = ['doc.txt', 'stuff.rtf', 'artfunction.exe', 'rtfunc.bat', 'doc2.rtf'] print('\n'.join(filename for filename in fnmatch.filter(files, pattern))) [/CODE]

Member Avatar for TrustyTony
0
351
Member Avatar for rssk

A classical method using list comprehensions [CODE] dict([(list[i], list[i+1]) for i in range(0, len(list), 2)]) [/CODE] function dict takes a list of tuples for arguments and uses the first term of the tuple as key and the second as value If you need more explanations, don't hesitate to ask.

Member Avatar for woooee
0
102
Member Avatar for blacknred

you have to do [code] folder = r'\\192.168.0.12\myshare1' # OR folder = '\\\\192.168.0.12\\myshare1' [/code]

Member Avatar for jice
0
130
Member Avatar for ThePythonNoob

Something like this : [CODE] import random class TV(object): def __init__(self): # self refers to the object itself # Don't mix up an object instance and an object class. # Class is the definition of a type of object (for example TVs all have a brand and channels) # instance …

Member Avatar for lrh9
0
210
Member Avatar for D_rOiD

Here are some function you can look at : - os.listdir(mydir) will list all the files from "mydir" - fnmatch.filter(files_list, "*.txt") will give you a list of all text files in the files_list (tip : fnmatch.filter(os.listdir(mydir)) - os.path.join(mydir, file) will give you the absolute name of the file - os.walk(mydir) …

Member Avatar for jice
0
4K
Member Avatar for tony75

[CODE] import glob print "\n\n".join(["".join([l for l in open(inf).readlines()[:2]]) for inf in glob.glob("C:\\path\\to\\the\\dir\\*.txt")]) [/CODE]

Member Avatar for TrustyTony
0
268
Member Avatar for animanga

Hi, You can use () to make it work (if you really want a one liner)... [CODE] def l(): return (lambda ...)() [/CODE] [CODE] def l(): return (lambda x=input("Enter the text to be decrypted: "),y=int(input("Enter the shift amount: ")): print("The decrypted text is: "+"".join(list(map(lambda x: chr(ord(x)+y),x)))))() [/CODE]

Member Avatar for animanga
0
760
Member Avatar for Zaffron

Can you put the code you use for writing the content of the chest (i suppose : chest.printChest()) and the datas that are written ? BTW, for this kind of thing, you should have a look at __repr__ function.

Member Avatar for woooee
0
462
Member Avatar for xxhellothere

[QUOTE=richieking;1491374][CODE]print(["/".join(date.split("-"))])[/CODE] 2011/03/03 from my htc phone ;)[/QUOTE] I'd rather do [CODE] date.replace('-','/') [/CODE]

Member Avatar for jice
0
163
Member Avatar for dustbunny000

You can try this : [CODE] protein="GWEIQPYVWDECYRVFYEQLNEEHKKIFKGIFDCIRDNSAPNLATLVRVTTNHFTHEQAMMDAVKFSEVLPHKKMHRDFLEKLGGLSAPVDNHIKGTDFKYKGKAKNVDYCKEWLVL" pp="LLCCCCCCCCCCCCCCCCCCHHHHHHHHHHHHHHHHHCHHHHHHHHHHHHHHCCCCHHHHHHHCLLLCCCCCHHHHHHHHHHHHHHHHHHHCCCCCCCCCCCHHHHHHHHHHHHCCL" gor="cccccccccccchhhhhhhhhhhhhhhhhhhhhhhccccccccceeeeecccccchhhhhhhhhhhcccchhhhhhhhhhhhhccccccccccccccccccccccceeceeccceec" aber="CCCCCCCCCCCCHHHHHHHCCHHHCHHHHHHHHHHCCCCHHHHHHHHHHHCCCCCCHHHHHHHCCCCCCCHCCHHHHHHHHHHCCCCCCCCCCCCCCCCCCCCCCCCCHHHHHHHCC" print "".join([str(i / 10) for i in range(len(protein))]) print "".join([str(i) for i in range(len(protein))]) print protein print pp print gor print aber [/CODE]

Member Avatar for jice
0
232
Member Avatar for jice

Hello there, I'm trying to generate a open office text document with tables generated from a database with the lpod library. I'd like to set the width of the tables columns but i can't manage it. Here is my test code so far : [code] import lpod.document import lpod.table doc …

Member Avatar for jice
0
161
Member Avatar for jice

hi, I try to write a app to automatically re-organize my mails (thunderbird). The first thing I try is to re-create my folders tree, once for each year. So i need to read mbox files and rewrite them [CODE=python] import mailbox mbx=mailbox.mbox("./in_mbox") mbx.lock() of=open("out_mbox", "w") for k, m in mbx.iteritems(): …

Member Avatar for jice
0
185
Member Avatar for novice20

This should work (not tested) [CODE] of = open(my_out_filename, 'w') for line in open(my_in_filename,'r'): if 'STRING' in line or 'INTEGER' in line: of.write(line) of.close() [/CODE]

Member Avatar for ptmcg
0
230
Member Avatar for novice20

You can generate csv files... For an easy csv management, there is a csv module [url]http://docs.python.org/library/csv.html[/url]

Member Avatar for jice
0
49
Member Avatar for acrocephalus

Have a look at this : [URL="http://www.devshed.com/c/a/Python/Database-Programming-in-Python-Accessing-MySQL/"]http://www.devshed.com/c/a/Python/Database-Programming-in-Python-Accessing-MySQL/[/URL] Others here [url]http://www.devshed.com/googlecse.html?cx=partner-pub-6422417422167576%3A6n32xsl5si9&cof=FORID%3A11&ie=ISO-8859-1&q=mysql+python&sa.x=28&sa.y=9&sa=Search&siteurl=www.devshed.com%2Fc%2Fb%2FPython%2F#1333[/url]

Member Avatar for acrocephalus
0
130
Member Avatar for lstensland

Your datas aren't in a csv format... For csv, here is a simple example to read and write datas [CODE] import csv # This class is to define another csv format if you need to class excel_french(csv.Dialect): delimiter=';' quotechar='"' doublequote=True skipinitialspace=False lineterminator='\n' quoting=csv.QUOTE_MINIMAL fic='yourfile.csv' outcsvfic='out.csv' csv.register_dialect('excel_french', excel_french) cr=csv.reader(open(fic,"r"), 'excel_french') # …

Member Avatar for lstensland
0
443
Member Avatar for albertkao

don't forget that, in os.walk, if you remove a dir from "dirs", it's subtree won't be explored. So [code] for dirpath, dirs, files in os.walk(path): for d in dirs: if d.startswith('.'): dirs.remove(d) # d's subtree won't be explored for f in files: if not f.startswith('.'): process_file() [/code]

Member Avatar for jice
0
3K
Member Avatar for macca21

A better way to deal with text files is rather with for loop : [code] of=open(myoutfilename, 'w') for line in open(myfilename,'r'): print line of.write(line.replace(' ', '\t')) of.close() ######### OR ############## # not sure the 2 with on the same line work (and i can't test it right now) # this …

Member Avatar for TrustyTony
0
194
Member Avatar for jpl1993
Member Avatar for jpl1993
Member Avatar for dbphydb

wherever you write : [code] something("%s") % one_variable [/code] write [code] something("%s" % one_variable) [/code]

Member Avatar for dbphydb
0
113
Member Avatar for notuserfriendly

Just one thing. For line iterating, i find it is a bad idea to load the whole file in a list (using readlines()) except if you can't process it sequentially. This will consume memory for really nothing interesting... Python allows iterating directly on file lines : [CODE] for line in …

Member Avatar for woooee
0
508
Member Avatar for pankajpriyam

Sorry but i don't understand what you want... Can you post your code ? part of your sql files ? How do you execute the content of your sql files ? What do you want to write in your logfile ? Your question in far too open for me to …

Member Avatar for jice
0
100
Member Avatar for Dan08

Fast method, using sets : [CODE] lines=open(myfile,'r').readlines() uniquelines=set(lines) open(outfile,'w').writelines(uniquelines) [/CODE] which can be done in only one line : [CODE] open(outfile,'w').writelines(set(open(myfile,'r').readlines())) [/CODE]

Member Avatar for TrustyTony
0
4K
Member Avatar for mahela007

You can do a list of lists... [CODE] rows=[[],[],[]...] # you call a particular cell by doing rows[3][4] [/CODE]

Member Avatar for mahela007
0
359
Member Avatar for sob_andizzle

[quote=soulmazer;1188565] edit: Admins/moderators, how do you put a code tag in a reply without creating a code box?[/quote] Hou can put spaces after the opening or before the closing [ ] [code ] [/code ]

Member Avatar for jice
0
145
Member Avatar for kur3k

Problem 1 (done with python 2.4) [CODE] # -*- coding: latin-1 -*- # The first line is important and must be consistant with your file encoding (maybe utf8) import string t=string.maketrans('àéèëêôöîïù', 'aeeeeooiiu') print "lévitèrent à l'ïstrùmen".translate(t) [/CODE] for python 3.1 [CODE] # -*- coding: latin-1 -*- t=str.maketrans('àéèëêôöîïù', 'aeeeeooiiu') print ("lévitèrent …

Member Avatar for jice
0
670
Member Avatar for goodwin912

Here is some kind of skeleton to copy your files (you'll have to adapt it but the principle is here) : [CODE] import os, fnmatch, shutil mydir="/path/to/my/dir/" for filename in fnmatch.filter(os.listdir(mydir),'*.py'): shutil.copy(filename, "anotherDir/new-%s" % filename) [/CODE] Note that if you want to explore the dir recursively, you can do: [CODE] …

Member Avatar for Tech B
0
232
Member Avatar for kjock002

Your way is so complicated : [CODE] def fileCount(filename): txt=open(filename).read() linecount=len(txt.split("\n")) wordcount=len(txt.split()) charcount=len(txt.replace("\n","")) # if you don't want tou count the '\n' return (linecount, wordcount, charcount) [/CODE]

Member Avatar for TrustyTony
0
2K
Member Avatar for Tops

You don't need to split and join... [CODE] datas = """US 9 15 13 37 GE 10 13 7 30 CA 14 7 5 26""".split("\n") for l in datas: print l.split(None,1)[1] # the 1 split argument will tell to split only once # Faster # you can also use lists …

Member Avatar for TrustyTony
0
2K
Member Avatar for vsagarmb
Member Avatar for jice
0
2K
Member Avatar for minimagician

Just translate what you think : [CODE] f = open('testread.txt') f1 = open('testread1.txt', 'a') doIHaveToCopyTheLine=False for line in f.readlines(): if 'this is the line i want to search' in line: doIHaveToCopyTheLine=True if doIHaveToCopyTheLine: f1.write(line) f1.close() f.close() [/CODE]

Member Avatar for rohini.vangury
0
7K
Member Avatar for davegball

I can see 2 solutions : [code=python] list1 = ["20100122 http google.com 200", "20100124 http hushmail.com 200", "20100123 http microsoft.com 404" ] list2 = ["google.com", "yahoo.com", "msn.com", "hotmail.com", "gmail.com"] # 1 for i, e1 in enumerate(list1): for e2 in list2: if e2 in e1: print ("line %d : %s" % …

Member Avatar for davegball
0
176
Member Avatar for peppermints

[CODE] score = score + scores(int) [/CODE] don't you mean [CODE] score = score + int(scores) [/CODE]

Member Avatar for woooee
0
196
Member Avatar for TotalyWired
Member Avatar for TotalyWired
-1
95
Member Avatar for gangemia

2 more solutions using dict() [code] datas="""Avenue,Av Road,Rd South East,SE Terrace,Tce""".split("\n") # The shortest way : print dict([(l.split(",")[0], l.split(",")[1]) for l in datas]) # a more understandable way lst=[] for l in datas: sl=l.split(",") lst.append((sl[0], sl[1])) d=dict(lst) print d [/code]

Member Avatar for jice
0
235
Member Avatar for sammakko

You problem is not clear to me : Why is ('1101','4') the correct output ? '1101' is in the second list... Why not ('4472', '4') or ('5419', '2') Are these tuples displayed if and only if the run id of the id in list 1 is greater than any run …

Member Avatar for sammakko
0
89
Member Avatar for edy_sze

[QUOTE=edy_sze;1127397] [CODE]def IntToNBytes(integer, n): while len(tmphex)<2*n: tmphex = '0'+tmphex [/CODE][/QUOTE] You should NOT do this. Adding characters to strings like this is very slow. You should use a list instead (eventually, if you need a string a the end, you can join it (''.join(mylist)) : [CODE] def IntToNBytes(integer, n): tmphex …

Member Avatar for edy_sze
0
137
Member Avatar for autobiography

[QUOTE=autobiography;1112150] [CODE]if x != int(x):[/CODE][/QUOTE] This will tell you whether x is an int or not but should raise a ValueError if x is a non digit string ('a' for example) and will be false is x is a digit string ('6' != 6) What you want to do is …

Member Avatar for autobiography
0
104
Member Avatar for deonis

This should do the trick [CODE]keywords=[word1,word2,wor3,word4] file1="/path/to/file1.txt" file2="/path/to/file2.txt" f2=open(file2).readlines() # I load the 2d file in a list to be able to change a line by another easily for l in open(file1): # no need to open the file and read it before. This will read the file line by …

Member Avatar for jice
-1
673
Member Avatar for tigrum

[QUOTE=tigrum;1006105]Hello, [CODE] c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row") [/CODE] [/QUOTE] Your "row" is inside the sql statement as a string ! You can do [CODE] c.execute("INSERT INTO a (first, last) VALUES (%s, %s)" % row) [/CODE]

Member Avatar for octav1
0
4K
Member Avatar for hondros

You should use modules like pickle or marshal to serialize and load your datas [code=python] import pickle c=['Hondros', {'Equiped': [['none', [], 0], ['Rags', [0, 1, 0, 0], 1, 1], ['Mocassins', [0, 0, 1, 0], 1, 1], ['Gauntlets', [0, 0, 0, 1], 6, 5]], 'Equipment': [0, 1, 1, 1], 'Stats': {'AC': …

Member Avatar for hondros
0
174
Member Avatar for AutoPython

You should run your program with pythonw. This can be done in your command line or by renaming your .py file .pyw

Member Avatar for sheeps
0
15K
Member Avatar for lewashby

You can have a look at this to have an idea of web programming in python [url]http://webpython.codepoint.net/[/url] and this [url]http://webpy.org/[/url] I've never done web programming in python because norm in my job is php so i had to learn php. And i find it much less pleasant to write. If …

Member Avatar for pythopian
0
634

The End.