Python Reading And Writing Files

python write to file
file = open(“testfile.txt”,”w”) 
 
file.write(“Hello World”) 
file.write(“This is our new text file”) 
file.write(“and this is another line.”) 
file.write(“Why? Because we can.”) 
 
file.close() 
python write to file
# using 'with' block

with open("xyz.txt", "w") as file: # xyz.txt is filename, w means write format
file.write("xyz") # write text xyz in the file

# maunal opening and closing

f= open("xyz.txt", "w")
f.write("hello")
f.close()

# Hope you had a nice little IO lesson
python open and read file with
with open('pagehead.section.htm','r') as f:
output = f.read()
python file reading
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
read files and write into another files python
import sys
import glob
import os.path

list_of_files = glob.glob('/Users/Emily/Topics/*.txt') #500 files

for file_name in list_of_files:
print(file_name)

# This needs to be done *inside the loop*
f= open(file_name, 'r')
lst = []
for line in f:
line.strip()
line = line.replace("\n" ,'')
line = line.replace("//" , '')
lst.append(line)
f.close()

f=open(os.path.join('/Users/Emily/UpdatedTopics',
os.path.basename(file_name)) , 'w')

for line in lst:
f.write(line)
f.close()
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()

Leave a Comment