python 学习笔记(File)

  • Open file
handle = open(filename,mode)
returns a handle use to manipulate the file. 
  • Processing files
 xfile = open('test.txt')
for cheese in xfile:
   print(cheese)
  • Counting Lines in a File
fhand = open('test.text')
count = 0
for line in fhand:
  count = count +1
print('Line Count', count)
  • Reading the 'whole' File
fhand = open('test.txt')
inp = fhand.read()
print(len(inp)
print(inp[:20])
  • Searching Through a File
fhand = open('test.txt')
for line in fhand:
  line = line.rstrip() #ignore the \n
  if line.startswith('from'):
    print(line)

alternative way

for line in fhand:
   line = line.rstrip()
   if not line.starswith('from'):
    continue
   print(line)
  • Count frenquency
counts = dict()
names = ['hello','youtube','yes','hello']
for name in names:
  if name not in counts:
    counts[name] = 1
   counts[name] = counts[name] + 1

or

counts = dict()
names = ['hello','youtube','yes','hello']
for name in names:
  counts[name] = counts.get(name,0) +1

你可能感兴趣的:(python 学习笔记(File))