xxxxxxxxxx
# write data in a file.
file1 = open("SofthuntFile1.txt","w")
multiple_string = ["This is Mango \n","This is Apple \n","This is Banana \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(multiple_string)
file1.close() #to change file access modes
file1 = open("SofthuntFile1.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
xxxxxxxxxx
# How to read, and print to the screen a file in python!
f = open('fileName', 'r')
print(f.read())
f.close()
# Where "fileName" is obviously the name of your file that you want to read.
xxxxxxxxxx
with open('example.txt', 'r') as file:
contents = file.read()
print(contents)
This code will read the entire contents of the example.txt file and print it to the console.
You can also read the contents of a file line by line using the readline() method. Here's an example:
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
This code will read the example.txt file line by line and print each line to the console.
I hope it will help you. Thank you :)
For more refer link: https://www.programmingquest.com/2023/03/how-to-work-with-files-in-python.html
xxxxxxxxxx
fileName = "file_name.txt" #Here you need to write the file name as a string
openLike = "" #Here you need to write how do you want to open the file:
#"w": Write, "r": Read
openedFile = open("file_name.txt", openLike) #Here you open the file
fileText = openedFile.read() #This read all the file
openedFile.close() #Close the file
print(fileText) # Prints the file text
xxxxxxxxxx
txt = open('FILENAME.txt')
txtread = txt.read()
print(txtread)
print(txt.read())
xxxxxxxxxx
my_file = open("C:\\Users\\Python\\file.txt", "r")
#Give the path accurately and use \\
text = my_file.read()
print(text)
#Output: The text in file.txt will be printed
xxxxxxxxxx
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()