Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python open file for reading and writing

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()
Comment

python reading and writing files

'''
You can read and write in files with open()
'r' = read
'w' = write (overwrite)
'a' = append (add)

NOTE: You can use shortened 'file.txt' if the file is in the same
directory (folder) as the code. Otherwise use full file adress.
'''

myFile = open('file.txt', 'r') # Open file in reading mode
print(myFile.read()) # Prints out file
myFile.close() # Close file

myNewFile = open('newFile.txt', 'w') # Overwrites file OR creates new file
myNewFile.write('This is a new line') # Adds line to text
myNewFile.close()

file = open('newFile.txt', 'a') # Opens existing newFile.txt
file.write('This line has been added') # Add line (without overwriting)
file.close()
Comment

open and write in a file in python

my_file = open("C:UsersPythonfile.txt", "w")
#Give the path accurately and use 
my_file.write("This is the test text")
my_file.close()

# It is always recommended to close the file after modifying
# to see the output, open the file - file.txt
Comment

PREVIOUS NEXT
Code Example
Python :: start django project in windows 
Python :: python json check if key exists 
Python :: stack queue in python 
Python :: discord get bot profile picture 
Python :: opencv shift image python 
Python :: how to make lists in python 
Python :: python rgb to hex 
Python :: requests save data to disk 
Python :: Python NumPy split Function Example 
Python :: who created python 
Python :: fillna method 
Python :: dropna threshold 
Python :: how to do a mac vendor lookup in python 
Python :: install a lower version of python using conda 
Python :: how to concat on the basis of particular columns in pandas 
Python :: check if year is leap python 
Python :: intellij python 
Python :: sqlalchemy create engine MySQL 
Python :: python optional arguments 
Python :: python thread function 
Python :: how to show a frequency distribution based on date in python 
Python :: run in thread decorator 
Python :: how to install tkinter in pycharm 
Python :: slice notation python 
Python :: pandas convert numbers in parentheses to negative 
Python :: remove from string python 
Python :: windows error message python 
Python :: django celery results 
Python :: how to find the speed of a python program 
Python :: python put console window on top 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =