zbz323
0
Q:

with open python

with open(filename,"w") as f:
  f.write('Hello World')
15
with open('output.txt', 'w') as file:  # Use file to refer to the file object

    file.write('Hi there!')
1
#there are many modes you can open files in. r means read.
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()

#you can write a string to it, too!
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')

#don't forget to close it afterwards!
file.close()
6
# Reference https://docs.python.org/3/library/functions.html#open

# Method 1
file = open("welcome.txt", "r") # mode can be r(read) w(write) and others 
data = file.read()
file.close()

# Method 2 - automatic close
with open("welcome.txt") as infile:
  data = file.read()
4
>>> with open('workfile') as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True
3
def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')
1
with open('output.txt', 'w') as file:  # Use file to refer to the file object

    file.write('Hi there!')
0

f = open("demofile.txt", "bt")
 
0
file_object  = open("filename", "mode") 
0

New to Communities?

Join the community