써니(>_<) 2022. 7. 17. 07:39

create file 

# opening a file in write mode will either create a new file (if the file does not exist) 
# or overwrite an existing one

f = open('test.txt', 'w')

read file 

f = open('test.txt', 'r')

contents = f.read() # read the entire file content
print(contents)

contents = f.read(10) # read only the first 10 characters of the file
print(contents)

line = f.readline() # read first line of the file
print(line)

for line in f.readlines(): # read the contents of the file line by line
print(line)

 

write file 

# creating a new file for writing (or over writing)
f = open('test.txt', 'w')
f.write('First line')
f.write('Still the First line\n')
f.write('second line\n')

# open file for appending with 'a’
f = open('test.txt', 'a')
f.write('This string is added...')
f.write('to the existing')

# to save the changes to the file and make
# it available for reading, it must be closed!
f.close()

 

with statement 

: The withstatement will bind the opened file handle to a variable and it will automatically handle the closingat the end of the block.

with open('test.txt', 'w') as f:
	f.write('...')

with open('test.txt', 'r') as f:
	print(f.read())