Python, cannot open a text file - python

I have a text file named android.txt (with a couple of thousand of lines) which I try to open with python, my code is:
f = open('/home/user/android.txt', 'r')
But when I'm doing:
f.read()
the result is:
''
I chmod 777 /home/user/android.txt but the result remains the same

You are not displaying the contents of the file, just reading it.
For instance you could do something like this:
with open('/home/user/android.txt') as infp:
data = infp.read()
print data # display data read
Using with will also close the file for your automatically

The result would be empty string not empty list and it's because your file size is larger than your memory(based on your python version and your machine)! So python doesn't assigned the file content to a variable!
For getting rid of this problem you need to process your file line by line.
with open('/home/user/android.txt') as f :
for line in f:
#do stuff with line

Related

File handling techniques in Python

How do I read a file by opening that particular file instead of printing it on the console? I've used the following code but it prints the contents of the file on the console.
fw=open("x.txt",'r+')
#fw.write("Hello\n")
#fw.write("Python is crazy af")
n=fw.read()
print(n)
fw.close()
The builtin open function makes the contents of a file available, meaning you can manipulate it with your code. If you don't want to print a line of it, you can do .readlines(). If you don't want to print it you can do anything else you want with it like store it in a variable.
One last note about file context:
with open("filename.txt", "r") as file:
for line in file:
# Do something with line here
This pattern is guaranteed to close, instead of calling open and close separately.
But if you wanted to open a text editor...
https://stackoverflow.com/a/6178200/10553976
How do I read a file by opening that particular file
The first 2 (non comment) lines of your answer do this:
fw=open("x.txt",'r+')
n=fw.read()
You have now read the contents of x.txt into the variable n
instead of printing it on the console?
Don't print it then. Remove the line
print(n)
and the contents of the file won't be printed.

How do you permanently write to a text file in Python?

I am able to write to a text file using .write(). But after I close() the file and open it again all the written data is gone...? Is there any way that I can permanently save this data on the file?
def writeToFile():
myFile = open("myText.txt","w")
for each in range(8,10):
record = "This is record number {} in the file\n".format(each)
myFile.write(record)
myFile.close()
writeToFile()
So what i meant was that the first time i run this program it appends to the file. After this when i close the program and run it again i want it to write to the file again, but instead it only overrides it, i.e the earlier data is deleted each time i close the program.
The data you wanted to write was indeed permanently written... until you opened again overwriting the previous data.
You have different modes to open the file.
If you know that the file has important data and only want to read it, use this mode.
file = open('./path_to_file', 'r')
If you want to overwrite the data, use this one instead:
file = open('./path_to_file', 'w')
Optionally, you can use this other way instead, and it will close the file for you.
with open('./path_to_file', 'r') as read_file:
for line in read_file:
print line
This will open the file, read it line by line writing it on the screen and closing it for you at the end.
Finally, if you need to open it again and append new content at the end of the file, just use this:
file = open('./path_to_file', 'a')

How do I print the content of a .txt file in Python?

I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.
I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:
from sys import argv
script, filename = argv
print "Who are you?"
name = raw_input()
print "What file are you looking for today?"
file = raw_input()
print (file)
print "Ok then, here's the file you wanted."
print "Would you like to delete the contents? Yes or No?"
I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip() remove notations like this: /n
print ''.join(file('example.txt'))
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
single line to read/print contents of a file
reading file : example.txt
print(open('example.txt', 'r').read())
output:
u r reading the contents of example.txt file
Reading and printing the content of a text file (.txt) in Python3
Consider this as the content of text file with the name world.txt:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read() like this:
content_of_file= file.read()
Finally we will just print the content_of_file variable using print command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!

How can I incorporate a text file into the body of my Python script?

Currently, my code is reading an external text file, using:
text_file = open("file.txt", 'r', 0)
my_list = []
for line in text_file
my_list.append(line.strip().lower())
return my_list
I would like to send my code to a friend without having to send a separate text file. So I am looking for a way of incorporating the content of the text file into my code.
How can I achieve this?
If I convert the text file into list format ([a, b, c, ...]) inside MS notepad using replace function, and then try to copy & paste list into Python IDE (I'm using IDLE), the process is hellishly memory intensive: IDLE tries to string out everything to the right in one line (i.e. no word wrap), and it never ends.
I'm not totally sure what you're asking, but if I'm guessing what you mean correctly, you could do this:
my_list = ['line1', 'line2']
Where each is a line from your text file.
Just put all the file contents into ONE MASSIVE string:
with open('path/to/my/txt/file') as f:
file_contents = f.read()
So now, your friend can do:
for line in file_contents.split('\n'):
#code
which is equivalent to
with open('path/to/file') as f:
for line in f:
#code
Hope this helps
I would suggest
assign the contents of the file to a variable in another py file
read the value by importing it in you program
that way the py file will be converted to pyc (send that), or py2exe will take care of it..
and would not allow your friend to mess with the contents...
You could also do something like:
my_file_contents = """file_contents_including_newlines"""
for line in my_file_contents.split('\n'): # Assuming UNIX line ending, else split '\r\n'
*do something with "line" variable*
Note the use of triple quotes around the text to be sent. This would work for non-binary data.

Python: Write to next empty line

I'm trying to write the output of something that is being done over three big iterations and each time I'm opening and closing the outfile. Counters get reset and things like this after the iterations and I'm a massive newb and would struggle to work around this with the shoddy code I've written. So even if it's slower I'd like change the way it is being output.
Currently for the output it's just rewriting over the first line so I have only the output of the last run of the program. (tau, output are variables given values in the iterations above in the code)
with open(fileName + '.autocorrelate', "w") as outfile:
outfile.writelines('{0} {1}{2}'.format(tau, output, '\n'))
I was wondering if there are any quick ways to get python to check for the first empty line when it opens a file and write the new line there?
Open with "a" instead of "w" will write at the end of the file. That's the way to not overwrite.
If you open your file in append mode : "a" instead of "w", you will be able to write a new line at the end of your file.
You do do something like that to keep a reference (line number) to every empty line in a file
# Get file contents
fd = open(file)
contents = fd.readlines()
fd.close()
empty_line = []
i = 0
# find empty line
for line in contents:
if line == "":
empty_line.append(i)
i+=1

Categories

Resources