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!
Related
and thank you for taking the time to read this post. This is literally my first time trying to use Python so bare with me.
My Target/Goal: Edit the original text file (Original .txt file) so that for every domain listed an "OR" is added in between them (below target formatting image). Any help is greatly appreciated.
I have been able to google the information to open and read the txt file, however, I am not sure how to do the formatting part.
Script
Original .txt file
Target formatting
You can achieve this in a couple lines as:
with open(my_file) as fd:
result = fd.read().replace("\n", " OR ")
You could then write this to another file with:
with open(formatted_file, "w") as fd:
fd.write(result)
something you could do is the following
import re
# This opens the file in read mode
with open('Original.txt', 'r') as file:
# Read the contents of the file
contents = file.read()
# Seems that your original file has line breaks to each domain so
# you could replace it with the word "OR" using a regular expression
contents = re.sub(r'\n+', ' OR ', contents)
# Then you should open the file in write mode
with open('Original.txt', 'w') as file:
# and finally write the modified contents to the file
file.write(contents)
a suggestion is, maybe you want to try first writing in a different file to see if you are happy with the results (or do a copy of Original.txt just in case)
with open('AnotherOriginal.txt', 'w') as file:
file.write(contents)
I want to save ''contents'' to a new text file in python. I need to have all the words in lowercase to be able to find the word frequency. '''text.lower()''' didn't work. Here is the code;
text=open('page.txt', encoding='utf8')
for x in text:
print(x.lower())
I want to save the results of print to a new text file. How can I do that?
You can use file parameter in print to directly print the output of print(...) to your desired file.
text=open('page.txt', encoding='utf8')
text1=open('page1.txt', mode='x',encoding='utf8') #New text file name it according to you
for x in text:
print(x.lower(),file=text1)
text.close()
text1.close()
Note: Use with while operating on files. As you don't have to explicitly use .close it takes care of that.
You are opening the file page.txt for reading, but it's not open to write. Since you want to save to a new text file, you might also open new_page.txt where you write all of the lines in page.txt lowercased:
# the with statement is the more pythonic way to open a file
with open('page.txt') as fh:
# open the new file handle in write mode ('w' is for write,
# it defaults to 'r' for read
with open('new_page.txt', 'w') as outfile:
for line in fh:
# write the lowercased version of each line to the new file
outfile.write(line.lower())
The important thing to note is that the with statement negates the need for you to close the file, even in the case of an error
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("yourfilename.txt", "w")
#Do whatever you need to write on the file here.
sys.stdout.close()
sys.stdout=stdoutOrigin
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.
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
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.