Question about how to read or write files

0 Саво Ђокић · August 21, 2015
How I can read some random file from my computer? Text or something else? 

Post a Reply

Replies

Oldest  Newest  Rating
0 Otto Von Chesterfield · August 23, 2015
Yes, you can! You need to use the open() method to do so.

file = open('path/some_file.txt', 'r') # The 'r' means that you want to read the file.


#Read Line by Line
line = file.readLine()
while line != '':
print(line)
line = file.readLine()

file.close() #Good practice to close files after you're done.


You can also read the whole file in one go!
file = open('path/some_file.txt', 'r')
print( file.read() )
file.close()


To write files, you can do:
line = input("Type to Write in File>")
file = open('path/new_file', 'w') #The 'w' means that you want to write.
file.write(line)
file.close()


Tell me if this helps!
0 Vadim Kotlarov · August 24, 2015
There is actually a nice shortcut if you need a relative path and you won't necessarily use the same computer (Or just useful to know nonetheless):

from os.path import dirname

folder_name = dirname(__file__)

In folder_name you will have the path of the folder that your current code is in.

You can instead import the entire os package, though it is a waste of resources unless you need more functions from it:
import os

folder_name = os.path.dirname(__file__)

To that you can add the relative path of the file that you want to open.
file = open(folder_name + 'readme.txt') 
#As Otto said, 'r' after the file path is for reading, but it is also the default value so can be skipped

After this you will have to close the file in the end of the use.

A different way to use files in Python is using the command "with". This command leaves the file (Or url) connection open until you are out of the indentation for it and then it closes it (Similar to function use).

Example:

with open(os.path.dirname(__file__)+r"\file.txt") as f:
     lines = list(f)  #This actually reads the entire file into a list that is split based on lines in the file,
                      # useful for small size of text files.
#Here the file is already closed but "lines" is still an active list variable.
  • 1

Python

107,039 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator