How to Open a file through python
You can easily pass the file object.
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable.
and in your function, return the list of lines
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
Another trick, python file objects actually have a method to read the lines of the file. Like this:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
With the second method, readlines
is like your function. You don't have to call it again.
Update
Here is how you should write your code:
First method:
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable (list).
print(contents)
Second one:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
print(contents)
Hope this helps!
How can I open files in external programs in Python?
Use this to open any file with the default program:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("start " + fileName)
If you really want to use a certain program, such as notepad, you can do it like this:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("notepad.exe " + fileName)
Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.
How to open a text file from my desktop while using python 3.7.1 in Terminal
As @Matt explained, you are missing quotes.
You can follow below approach to open file and read from it.
myfile = open("/Users/David/Desktop/test.txt","r") #returns file handle
myfile.read() # reading from the file
myfile.close() # closing the file handle, to release the resources.
For more information on how to do read/write operations on file
How do I create and open files through Python?
openfile = open('test_readline', 'w')
^^
Opening in write
mode will create the file if it doesn't already exist. Now you can write into it and close the file pointer and it will be saved.
open() in Python does not create a file if it doesn't exist
You should use open
with the w+
mode:
file = open('myfile.dat', 'w+')
Launch a shell command with in a python script, wait for the termination and return to the script
subprocess: The
subprocess
module
allows you to spawn new processes,
connect to their input/output/error
pipes, and obtain their return codes.
http://docs.python.org/library/subprocess.html
Usage:
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
How to open every file in a folder
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import os, glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
import os, glob
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And you can then use it with piping:
ls -1 | python parse.py
How to open and edit an existing file in Python?
this link maybe will be help,
the code such as
# Open a file
fo = open("foo.txt", "a") # safer than w mode
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
How to open an HTML file in the browser from Python?
Try specifying the "file://" at the start of the URL.
// Also, use the absolute path of the file:
webbrowser.open('file://' + os.path.realpath(filename))
Or
import webbrowser
new = 2 # open in a new tab, if possible
// open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.open(url,new=new)
// open an HTML file on my own (Windows) computer
url = "file://d/testdata.html"
webbrowser.open(url,new=new)
How to open a file using the open with statement
Python allows putting multiple open()
statements in a single with
. You comma-separate them. Your code would then be:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
And no, you don't gain anything by putting an explicit return
at the end of your function. You can use return
to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return
to specify the value to return.)
Using multiple open()
items with with
was not supported in Python 2.5 when the with
statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer.
http://docs.python.org/reference/compound_stmts.html#the-with-statement
http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement
If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with
statements as the other answers suggested or use contextlib.nested
.
Related Topics
Python Saving Multiple Figures into One PDF File
Installing Module from Github Through Jupyter Notebook
Running a Tkinter Form in a Separate Thread
Convert a 1D Array to a 2D Array in Numpy
Install MySQL-Python (Windows)
String Comparison Doesn't Seem to Work for Lines Read from a File
Python Daemon and Systemd Service
Removing Horizontal Lines in Image (Opencv, Python, Matplotlib)
How to Add an Empty Column to a Dataframe
Why Does Python's Multiprocessing Module Import _Main_ When Starting a New Process on Windows
Python Matplotlib Figure Title Overlaps Axes Label When Using Twiny
Python Argparse Ignore Unrecognised Arguments
Accessing CPU Temperature in Python
Trying to Delay a Specific Function for Spawning Enemy After a Certain Amount of Time