廣告

2015年3月7日 星期六

[python] FILE I/O (read) & to Dictionary | FILE I/O (write) & input(raw_input)


readFile.py
import pickle
#save object type

file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part



print people

print '=========use pickle======'

file.close()

pick = open('picktest.txt','w')
pickle.dump(people,pick)
pick.close

pick = open('picktest.txt')
people = pickle.load(pick)
print(people)


consol
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

{'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], 'jim': ['3', 'jim', '170', '60'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}
=========use pickle======
{'jim': ['3', 'jim', '170', '60'], 'lewis': ['1', 'lewis', '183', '70'], 'fai': ['5', 'fai', '180', '70'], '7': ['4', '7', '170', '80'], 'leo': ['2', 'leo', '175', '80']}


people.txt

1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70


writeFile.py
#inpput can't get blank

count = input("input how many people:")

list = []

for x in range(count):
        print 'input number name height weight,splite by blank'
        a = raw_input("-->:")
        list.append(a)


print 'your input is ' ,list


f = open('people2.txt','w')
for x in list:
        f.write(x+"\n")

f.close()

consol

([pythonTutorai])lewis@lewis-virtual-machine:~/pythonTutorial/tutorial2$ python writeFile.py
input how many people:3
input number name height weight,splite by blank
-->:6 aa 134 11
input number name height weight,splite by blank
-->:7 bb 431 233
input number name height weight,splite by blank
-->:8 cc 167 70
your input is  ['6 aa 134 11', '7 bb 431 233', '8 cc 167 70']

people2.txt
6 aa 134 11
7 bb 431 233
8 cc 167 70

沒有留言:

張貼留言