File handling techniques in Python - 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.

Related

Python script not finding value in log file when the value is in the file

The code below is meant to find any xls or csv file used in a process. The .log file contains full paths with extensions and definitely contains multiple values with "xls" or "csv". However, Python can't find anything...Any idea? The weird thing is when I copy the content of the log file and paste it to another notepad file and save it as log, it works then...
infile=r"C:\Users\me\Desktop\test.log"
important=[]
keep_words=["xls","csv"]
with open(infile,'r') as f:
for line in f:
for word in keep_words:
if word in line:
important.append(line)
print(important)
I was able to figure it out...encoding issue...
with io.open(infile,encoding='utf16') as f:
You must change the line
for line in f:
to
for line in f.readlines():
You made the python search in the bytes opened file, not in his content, even in his lines (in a list, just like the readlines method);
I hope I was able to help (sorry about my bad English).

Reading a simple .txt file with python, why does this simple code output every line? How does python know it should do that?

New to programming, newer to python ;) trying to learn file operations.
I dont understand how the code below works. what happens when open() is called with a for loop and why is this different to another python function .read(number_of_elements) ?
i have a test.txt file which is just numbered from 1) to 10), each on a new line. So a txt file with 10 lines. Why does python show the whole txt file using this for loop? Why does it know to print every line, at each new line? is it because Python converts the .txt into a list and then loops through it?
i have tried doing
print(f)
but this returns some information about the test.txt file, and did not print the content of the file like i expected.
python code:
with open("test.txt", "r") as f:
for line in f:
print(line)
test.txt file:
1)
2)
3)
4)
...
is it because Python converts the .txt into a list and then loops through it
Effectively, yes. The code can be rewritten as:
file = open("test.txt", "r")
for line in file:
print(line)
file.close()
There is a bit of "magic" involved, but basically the File object in file knows that if it's being iterated on (via for line in file), it should give one line per each iteration.
Iterating a file per-line is often what you want to do - so python offers a quick and easy way to do just that. If you want the whole file in a single variable, there's also a method for that.
The variable f is your whole document.
Let's talk about with the for line in f::
By using this line you are looping through each line of the text file. so each time in the loop the value of line is your new line of file and when the print(line) runs it will print each line for you with a \n which means goes to next line.
You can reach more examples and information using this link: File
in Python

How to delete a line from a file in Python

I tried to use this: Deleting a line from a file in Python. I changed the code a bit to suit my purposes, like so:
def deleteLine():
f=open("cata.testprog","w+")
content=f.readlines()
outp = []
print(f.readline())
for lines in f:
print(lines)
if(lines[:4]!="0002"):
#if the first four characters of a line do not equal
outp.append(lines)
print(outp)
f.writelines(outp)
f.close()
The problem is that the entire file gets replaced by an empty string and outp is equal to an empty list. My file is not empty, and I want to delete the line that begins with "0002". Printing f.readline() gave me an empty string. Does anyone have any idea of how to fix it?
Thanks in advance,
You changed the file handling completely compared to the linked question. There, the file is first opened to read the content, closed and then opened to write the processed content. Here you open it and you first use f.readlines(), so all the data of the file is in content and the file pointer is at the end of the file.
You have opened file in wrong mode: "w+". This mode is used for writing and reading, but at first it is truncated. At first open file for reading. If it is not huge file read it into memory, convert there and save it by opening file in write mode.

What is the difference between opening and reading a file in python?

In python's OS module there is a method to open a file and a method to read a file.
The docs for the open method say:
Open the file file and set various flags according to flags and
possibly its mode according to mode. The default mode is 0777 (octal),
and the current umask value is first masked out. Return the file
descriptor for the newly opened file.
The docs for the read method say;
Read at most n bytes from file descriptor fd. Return a string
containing the bytes read. If the end of the file referred to by fd
has been reached, an empty string is returned.
I understand what it means to read n bytes from a file. But how does this differ from open?
"Opening" a file doesn't actually bring any of the data from the file into your program. It just prepares the file for reading (or writing), so when your program is ready to read the contents of the file it can do so right away.
Opening a file allows you to read or write to it (depending on the flag you pass as the second argument), whereas reading it actually pulls the data from a file that is typcially saved into a variable for processing or printed as output.
You do not always read from a file once it is opened. Opening also allows you to write to a file, either by overwriting all the contents or appending to the contents.
To read from a file:
>>> myfile = open('foo.txt', 'r')
>>> myfile.read()
First you open the file with read permission (r)
Then you read() from the file
To write to a file:
>>> myfile = open('foo.txt', 'r')
>>> myfile.write('I am writing to foo.txt')
The only thing that is being done in line 1 of each of these examples is opening the file. It is not until we actually read() from the file that anything is changed
open gets you a fd (file descriptor), you can read from that fd later.
One may also open a file for other purpose, say write to a file.
It seems to me you can read lines from the file handle without invoking the read method but I guess read() truly puts the data in the variable location. In my course we seem to be printing lines, counting lines, and adding numbers from lines without using read().
The rstrip() method needs to be used, however, because printing the line from the file handle using a for in statement also prints the invisible line break symbol at the end of the line, as does the print statement.
From Python for Everybody by Charles Severance, this is the starter code.
"""
7.2
Write a program that prompts for a file name,
then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point
values from each of the lines and compute the
average of those values and produce an output as
shown below. Do not use the sum() function or a
variable named sum in your solution.
You can download the sample data at
http://www.py4e.com/code3/mbox-short.txt when you
are testing below enter mbox-short.txt as the file name.
"""
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
print(line)
print("Done")

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!

Categories

Resources