Writing general script using open('file', 'r') - python

I am writing a script where I first read a file using
with open('file', 'r') as file,
do some operation, and then write it to a new file using
with open('newfile', 'w') as newfile.
My question is, what do I need to change in the script to make it general for a number of files, so that I can just call the script with the file name from the terminal like python3 script.py file.ext? Also, is there a way to write the output back into the original file using this method?

One way of doing this is:
import sys
file=open(sys.argv[1], "r")
newfile=open("example.txt", "w")
content=file.read()
#do stuff to content here such as content=content.upper()
newfile.write(content)
If you inputted into the command line:
python script.py aaaaaa.txt
Then the file you set as the output would have the edited content of aaaaaa.txt
Hope this helps :)

Related

Jupiter Notebook in vs code: python command not showing/ reading file from memory

my code is not showing any output after running specific commands for reading a file from storage location. I'm still a beginner so i'm little confused. Dropping my code here below
You are not reading the file your code, hence it does not show any output.
Try this
path = <path of you file>
file = open(path, mode="r")
file.read()
file.close()
You can also simplify it further
with open(path, mode="r") as file:
file.read()
If you want to display the output of an executed cell, you should execute the variable you want to inspect in a different cell (or at the end of a cell). It wont work if it is inside the context manager (with clause).
[1] with open(path, mode="r") as file:
content = file.read()
[2] content

Python:How do I export the output of my code to it's own text file?

How do I export the output of my code to it's own text file? When I run my code I get a large set of data from it. How do I export this so that I can read all lines of data in it's own text file.
You can write file in python like
with open("out.txt", "w") as f:
f.write("OUTPUT")
Or you can use io redirection to redirect output to a file
$ python code.py > out.txt
https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
https://en.wikipedia.org/wiki/Redirection_(computing)
Assuming you will read the results in another application, you can use redirections, usually something like this:
./myprogram >results.txt
You may want to take a look at file objects, which would allow you to write all the data you want to a file.
For example :
file = open('output.txt', 'w')
file.write('Here is some data')
file.close()
One way to do it is this:
import csv
with open("name_of_file_to_be_created") as f:
writer = csv.writer(f)
for i in range(n):
writer.writerow('stuff to write')
# writes a single line in each iteration, e.g. assuming you are computing something inside the loop
Another way to do this is:
with open("name_of_file_to_be_created") as f:
print("here you can type freely", file = f)
# or
f.write('whatever it is that you have to write')

create a file in the script using python

I am new to python.
I wanted to know if I could create a text file in the script itself before writing into.
I do not want to create a text file using the command prompt.
I have written this script to write the result into the file
with open('1.txt', 'r') as flp:
data = flp.readlines()
however I know that 1.txt has to be created before writing into it.
Any help would be highly appreciated.
Open can be used in a several modes, in your case you have opened in read mode ('r'). To write to a file you use the write mode ('w').
So you can get a file object with:
open('1.txt', 'w')
If 1.txt doesn't exist it will create it. If it does exist it will truncate it.
You can use open() to create files.
Example:
open("log.txt", "a")
This will create the file if it doesn't exist yet, and will append to it if the file already exists.
Using open(filename, 'w') creates the file if it's not there. Be careful though, if the file exists it will be overritten!
You can read more details here:

How to take input file from terminal for python script?

I have a python script which uses a text file and manipulate the data from the file and output to another file. Basically I want it to work for any text file input. Right now I readline from the file and then print the output to screen. I want the output in a file.
So user can type the following and test for any file:
cat input_file.txt | python script.py > output_file.txt.
How can I implement this in my script? Thank You.
cat is command in linux. I don't know how it works.
The best way to do this is probably to call the input and output files as arguments for the python script:
import sys
inFile = sys.argv[1]
outFile = sys.argv[2]
Then you can read in all your data, do your manipulations, and write out the results:
with open(inFile,'r') as i:
lines = i.readlines()
processedLines = manipulateData(lines)
with open(outFile,'w') as o:
for line in processedLines:
o.write(line)
You can call this program by running python script.py input_file.txt output_file.txt
If you absolutely must pipe the data to python (which is really not recommended), use sys.stdin.readlines()
This method (your question) describes reading data from STDIN:
cat input_file.txt | python script.py
Solution: script.py:
import sys
for line in sys.stdin:
print line
The method in above solutions describes taking argument parameters with your python call:
python script.py input_file.txt
Solution: script.py:
import sys
with open(sys.argv[1], 'r') as file:
for line in file:
print line
Hope this helps!
cat input_file.txt | python script.py > output_file.txt.
You can passing a big string that has all the data inside input_file.txt instead of an actual file so in order to implement your python script, just take that it as a string argument and split the strings by new line characters, for example you can use "\n" as a delimiter to split that big string and to write to an outputfile, just do it in the normal way
i.e. open file, write to the file and close file
Sending output to a file is very similar to taking input from a file.
You open a file for writing the same way you do for reading, except with a 'w' mode instead of an 'r' mode.
You write to a file by calling write on it the same way you read by calling read or readline.
This is all explained in the Reading and Writing Files section of the tutorial.
So, if your existing code looks like this:
with open('input.txt', 'r') as f:
while True:
line = f.readline()
if not line:
break
print(line)
You just need to do this:
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
while True:
line = fin.readline()
if not line:
break
fout.write(line)
If you're looking to allow the user to pass the filenames on the command line, use sys.argv to get the filenames, or use argparse for more complicated command-line argument parsing.
For example, you can change the first line to this:
import sys
with open(sys.argv[1], 'r') as fin, open(sys.argv[2], 'w') as fout:
Now, you can run the program like this:
python script.py input_file.txt outputfile.txt
cat input_file.txt | python script.py > output_file.txt
Basically, python script needs to read the input file and write to the standard output.
import sys
with open('input_file.txt', 'r') as f:
while True:
line = f.readline()
if not line:
break
sys.stdout.write(line)

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