Python2: Difference between revisions

From vwiki
Jump to navigation Jump to search
(Initial creation)
 
(→‎Files: Added additional examples)
Line 28: Line 28:
data = file.read()
data = file.read()
file.close()
file.close()
# Write a line to a file
log = open('test.log', 'w')
log.write('some text, no carriage return at end')
log.writelines('a line of text')
log.close


# Get directory listing and print with filesizes
# Get directory listing and print with filesizes
import os
files = os.listdir('dir')
files = os.listdir('dir')
for fil in files:
for fil in files:
     print (fil + '\t' + str(os.path.getsize(os.path.join('dir', fil))))
     print (fil + '\t' + str(os.path.getsize(os.path.join('dir', fil))))


# Move file
import shutil
shutil.move('file', 'dir/file')
</source>
</source>
[[Category:Python]]
[[Category:Python]]

Revision as of 08:58, 23 May 2011

Getting Started

The main site for downloads, documentation etc, can be found at http://www.python.org.

Python2 or Python3

The language is going through a metamorphosis from v2 to v3 and you'll have to choose which to go for. Essentially if you're starting from scratch then go for v3, but if you need to integrate with existing Python code or are a complete scripting/coding novice (and so need to be able to use the wealth of examples etc on the web) go for v2. See http://wiki.python.org/moin/Python2orPython3 for further info.

This page is for Python2

Install

Python often comes pre-installed on Linux systems such as Ubuntu, try firing up the command line environment by typing python. Otherwise you'll need to install from a repository (unix), or download and execute tyhe installer (windows).

Variables

Variable Information

Get a variables available methods...

dir(variable)

Variable Conversion

int(var)                # Convert to integer
str(var)                # Convert to string

Files

# Read contents of file
file = open('file.txt','r')
data = file.read()
file.close()

# Write a line to a file
log = open('test.log', 'w')
log.write('some text, no carriage return at end')
log.writelines('a line of text')
log.close

# Get directory listing and print with filesizes
import os
files = os.listdir('dir')
for fil in files:
    print (fil + '\t' + str(os.path.getsize(os.path.join('dir', fil))))

# Move file
import shutil
shutil.move('file', 'dir/file')