Skip to content

Commit 9189b6c

Browse files
committed
accessing files
1 parent 0a603cd commit 9189b6c

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

Files/File.txt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
Alas, poor Yorick! I knew him, Horatio: a fellow
2+
3+
of infinite jest, of most excellent fancy: he hath
4+
5+
borne me on his back a thousand times; and now, how
6+
7+
abhorred in my imagination it is! my gorge rims at
8+
9+
it. Here hung those lips that I have kissed I know
10+
11+
not how oft. Where be your gibes now? your
12+
13+
gambols? your songs? your flashes of merriment,
14+
15+
that were wont to set the table on a roar? Not one
16+
17+
now, to mock your own grinning? quite chap-fallen?
18+
19+
Now get you to my lady’s chamber, and tell her, let
20+
21+
her paint an inch thick, to this favour she must
22+
23+
come; make her laugh at that.

Files/files.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import os # imports os module
2+
3+
os.chdir(r'P:\Python Projects\Python-Notes\files') # set's the working directory for the python script:
4+
# Allows us to open File.txt without having to type the full file path in the open() method
5+
6+
ofile = open("File.txt") # To enable users to gain access to a file, we need to instantiate a variable
7+
# and assign it to the open() method, with the file name included in the parenthesis.
8+
# This doesn't read the file into the program, it more or less "imports" it and allows you to call it later
9+
# much like importing an additional python module
10+
11+
for i in ofile: # Python navigates files through line. This for statement with i as the loop counter
12+
# iterates through every line in the .txt file and subsequently prints the contents;
13+
# think of it as one giant array, where i instead of being the position in an array is the line in the file
14+
15+
print(i) # this algorithim allows a user to search through a file line by line using the .startswith() method
16+
if i.startswith("Alas,") : # if a line starts with a defined set of characters, in this case: "Alas," , then the print function is called
17+
print("Oh no!")
18+
19+
# The print() function in python automatically adds a new line after it reads the line from a txt file
20+
21+
rfile = ofile.read() #reads a file into memory
22+
count = 0
23+
for i in ofile :
24+
count = count + 1
25+
26+
print("there are ", count, " in this excerpt")

Strings/test.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)