Answers for "open file %in python"

6

read file python

document = 'document.txt'
file = open(document, 'r')
# 'r' to read.  it can be replaced with:
# 'w' to write (overwrite)
# 'a' to append (add to the end)
# 'w+' makes a new file if one does not already exist of that name
# 'a+' same as 'w+' but appends if the file does exist
# 'x' creates file for writing, but fails if file already exists

##go to beginning of document. not required but good for consistency.
file.seek(0)

##print all lines in document, except empty lines:
for line in file:
    k = line.strip() 
    print k

##close the file after you are done
file.close()


##this also works to open a file, and is more error proof:
with open(document) as filestream:
    for i in filestream:
        k = i.strip() 
        print k
Posted by: Guest on December-18-2019
11

python file open

#there are many modes you can open files in. r means read.
file = open('C:Usersyournamefilesfile.txt','r')
text = file.read()

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

#don't forget to close it afterwards!
file.close()
Posted by: Guest on March-26-2020
2

python open file

def main():
    f= open("guru99.txt","w+")
    #f=open("guru99.txt","a+")
    for i in range(10):
         f.write("This is line %drn" % (i+1))
    f.close()
    #Open the file back and read the contents
    #f=open("guru99.txt", "r")
    #if f.mode == 'r':
    #   contents =f.read()
    #    print (contents)
    #or, readlines reads the individual line into a list
    #fl =f.readlines()
    #for x in fl:
    #print(x)
if __name__== "__main__":
  main()
Posted by: Guest on February-21-2020

Python Answers by Framework

Browse Popular Code Answers by Language