0% found this document useful (0 votes)
3 views21 pages

ProgBasic2 File

Jskqdjw

Uploaded by

gimg6395
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

ProgBasic2 File

Jskqdjw

Uploaded by

gimg6395
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

.

File
memory hdd/ssd

Variables

Files

Python
Program
File
• string

• Line ‘\n’

• Python open .

I am a boy
second I am a boy\nsecond\nthird
third
test.txt
File open
• open .

open( , mode )
“test.txt” “r”
“out.dat” “w”
• mode “lina.jpg” “a”
• “r” : read, “w” : write, “a” : append

• return

• f = open(“test.txt”,”r”)

“r”
File
• “r” open

• f_in = open(“test.txt”,”r”)

• .

• read()

• readline()

• readlines()
for le
• –

fi
• open()
“ ”
• open( )

• r

• w

• w+

• a
• write( )

out = open(“data.out”, “w”)


out.write(“Hello! \n”)
• print( )

• ( )

• le

fi
(Flushing)


( )
for x in open(”test.txt”):
print(x)

OR

f = open(”test.txt”,”r”):
for x in f.readlines():
print(x)
( )
t = open(”output.txt”,”w”)
for x in data_list:
t.write(x)
t.close()
( )
t = open(”output.txt”,”w”)
for x in open(”input.txt”):
s = x.split()
t.write(s[0])
t.close()
CSV
• Comma-Separated Values

• ‘,’ 123,56,12412,102
842,12,341,921
91,8402,23,34412
199,2004,100,200

123, 56, 12412, 102\n


842, 12, 341, 921\n
4 rows 91, 8402, 23, 34412\n
199, 2004, 100, 200\n
4 columns
CSV
• (read) ‘,’ (split) .

>>> for line in open("data.csv","r"):


... t = line.split(",")
... print(t[1])
...
56
12
8402
2004
(integer)

( oating-point
numbers)
(string)
fl
(integer)
str()

int() oat()

str()
int()
( oating-point
numbers)
(string)

oat()
fl
fl
fl
CSV
>>> num = []
>>> for line in open("data.csv","r"):
... t = line.split(",")
... print(t[1])
... num.append( float( t[1] ) )
...
56
12
8402
2004
>>> num
[56.0, 12.0, 8402.0, 2004.0]
>>> sum(num)
10474.0

You might also like