xxxxxxxxxx
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
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
with open('filename', 'a') as f: # able to append data to file
f.write(var1) # Were var1 is some variable you have set previously
f.write('data')
f.close() # You can add this but it is not mandatory
with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)
with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail
with open('filename', 't') as f: # opens the file in text mode (also is defualt)
with open('filename', 'b') as f: # Use if your file will contain binary data
with open('filename', 'w') as f: # Open file with ability to write, will also create the file if it does not exist (if it exists will cause it to fail)
with open('filename', '+') as f: # Opens file with reading and writing
# You can combine these as you like with the + for reading and writing
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
lines = []
with open('the-zen-of-python.txt') as f:
lines = f.readlines()
count = 0
for line in lines:
count += 1
print(f'line {count}: {line}')
Code language: JavaScript (javascript)