reading files in python

You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.


Read file

You can read a file with the code below.
The file needs to be in the same directory as your program, if it is not you need to specify a path.


# Define your filename
filename = "file.py" 

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.readlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
    print(line),


The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.
If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:

content = f.read().splitlines()

Resulting in this code:



# Define a filename.
filename = "file.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
    print(line)







Comments

Popular posts from this blog

wifi attack with kali linux

how to clone a simcard ???