Open in TheBrain

Files Reading Writing Open Close DIRECTORY

<p>Feb 19, 2013 10:07 PM &#160;&#160;to get current working directory...

&#160;

&#62;&#62;&#62; &#160;import os &#160;&#160;&#160;# these functions are in the os module, which you need to open

&#62;&#62;&#62; &#160;os.getcwd() &#160;&#160;

'C:\Python27' &#160;&#160;&#160;# &#160;that's the dir you're connected to...

&#160;

&#160;

&#160;

Jan 24, 2013 05:09 PM &#160;FILES: &#160;Reading Writing Open and Close Files

&#160;

open takes a windows path as an argument &#160;eg

&#62;&#62;&#62; bob=open('C:\Python27\LICENSE.txt') &#160;&#160;&#160;...# note the path is a string;

&#160;

&#62;&#62;&#62; bob.close() &#160;# that will close the file object bob &#160;&#160;that's bob dot close.

bob = open('LICENSE.txt') &#160;&#160;# it <b>defaults to 'C:\Python27\' </b>&#160;&#160;....

&#160;

&#62;&#62;&#62; bob

&#60;open file 'LICENSE.txt', mode 'r' at 0x0000000002C79300&#62; &#160;&#160;# that is a file object (a pointer to a file).

license = bob.readlines() &#160;&#160;# license is the entire text of the license, read as strings delim. by CRLFs

each line ends in '\n' &#160;&#160;a CRLF

&#62;&#62;&#62; license[:3] &#160;&#160;&#160;&#160;# a list containing the first 3 entries

['A. HISTORY OF THE SOFTWARE\n', '==\n', '\n']

&#62;&#62;&#62; license[3] &#160;&#160;# the 4th entry

'Python was created in the early 1990s by Guido van Rossum at Stichting\n'

&#160;

&#62;&#62;&#62; aliceobject = open('alice','w') &#160;&#160;# creates a brand new file called alice in Python27 direc

&#160;

&#62;&#62;&#62; aliceobject.write('hello world')

&#62;&#62;&#62; aliceobject.close() &#160;&#160;# only AFTER closing the file, can you open it on Python27 with Notepad

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;#to see the hello world.

&#160;

&#160;also note... once a file exists, then you can read or write it with mode 'r+' &#160;nstead of 'w')

&#160;

&#62;&#62;&#62; 'klfjdlfd ieutoiweut 394853'.split(' ') =&#62; &#160;[strg1 ,strg 2 , &#160;strg3] &#160;# this SPLITs the string

&#160;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;# using space as the break char... ie delimited by whatever is btwn the quotes,

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;# &#160;so, &#160;'$' &#160;wll break at the $ .

&#160;

&#62;&#62;&#62; sample = "sljflksd$sljdlfsj$wioreu"

&#160;

&#62;&#62;&#62; sample

'sljflksd$sljdlfsj$wioreu'

&#160;

&#62;&#62;&#62; samplewords = sample.split('$')

&#160;

&#62;&#62;&#62; samplewords

['sljflksd', 'sljdlfsj', 'wioreu']

&#160;

&#160;

&#160;

&#160;

&#160;</p>