Difference between revisions of "Python:Files"
Jump to navigation
Jump to search
Line 10: | Line 10: | ||
;open (filename,"r") | ;open (filename,"r") | ||
− | :open | + | :open filename for read and return the filehandle. Use w for write. |
Code example: | Code example: | ||
Line 30: | Line 30: | ||
;f1.read(size) | ;f1.read(size) | ||
− | :Return 'size' | + | :Return 'size' bytes from the file as string. If size is omitted or 0 the entire file is returned. |
− | ;f1.readlines( | + | ;f1.readlines() |
;list(f1) | ;list(f1) | ||
− | :Return | + | :Return all lines from file as list. |
− | Read through all files specified on the commandline. | + | ;fileinput.input() |
− | If there are no files on the commandline read standard input | + | :Read through all files specified on the commandline. |
+ | :If there are no files on the commandline read standard input | ||
<syntaxhighlight lang=python> | <syntaxhighlight lang=python> | ||
import fileinput | import fileinput |
Revision as of 14:20, 16 March 2018
- glob.glob(filespec)
- Return a list of files matching 'filespec'.
Code example:
import glob
files = glob.glob(filespec)
- open (filename,"r")
- open filename for read and return the filehandle. Use w for write.
Code example:
import os
if os.path.isfile(filename):
f1 = open (filename,"r")
- with open (filename,"r") as file
- Open filename for read and close at the end of the loop
Code example:
with open (filename,"r") as file:
for line in file:
<codeblock>
- f1.read(size)
- Return 'size' bytes from the file as string. If size is omitted or 0 the entire file is returned.
- f1.readlines()
- list(f1)
- Return all lines from file as list.
- fileinput.input()
- Read through all files specified on the commandline.
- If there are no files on the commandline read standard input
import fileinput
for line in fileinput.input():
<codeblock>
Read from standard input and keyboard
Read from standard input
import sys
for line in sys.stdin:
<codeblock>
Prompt and read from keyboard into a
a = input("Prompt: ")
In python2
a = raw_input("Prompt: ")