learning Python the hard way argv and file - python

I am learning python from past weeks
from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
I want to view the contents of the file ,but when i use print filename or print filen it show name and open file on variable filen

you can read data using filen.read() or filen.readline() or filen.readlines()
1) read
fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()
2) readline
fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()
3) readlines.
fo = open(filename,read)
fo.readline() #read all the lines of a file in a list
fo.close()
Below document will give you better idea.
https://docs.python.org/2/tutorial/inputoutput.html

If you want to print the content of the file you opened, just use: print filen.read().

At its simplest:
from sys import argv
script,filename = argv
with open(filename) as f:
print f.readlines()
which dumps the files contents
or:
from sys import argv
script,filename = argv
with open(filename) as f:
lines=f.readlines()
for line in lines:
print line
which prints the lines out 1 by 1

Related

How to put all print output from cmd to a txt file?

Can you help me identify what's wrong in this code? I want to put all the print output on the cmd to a txt file. This code only puts the last line.
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
z = line.decode().strip()
with open('romeo.txt', 'w') as f:
print(z, file=f)
You are creating and writing 'romeo.txt' file for every line of the content. Swap the for loop and the opening file. Something like this:
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
with open('romeo.txt', 'w') as f:
for line in fhand:
z = line.decode().strip()
print(z, file=f)

How to erase line from text file in Python?

I'm trying to make a code to rewrite a specific line from a .txt file.
I can get to write in the line i want, but i can't erase the previous text on the line.
Here is my code:
(i'm trying a couple of things)
def writeline(file,n_line, text):
f=open(file,'r+')
count=0
for line in f:
count=count+1
if count==n_line :
f.write(line.replace(str(line),text))
#f.write('\r'+text)
You can use this code to make a test file for testing:
with open('writetest.txt','w') as f:
f.write('1 \n2 \n3 \n4 \n5')
writeline('writetest.txt',4,'This is the fourth line')
Edit: For Some reason, if i use 'if count==5:' the code compiles ok (even if it doen't erase the previous text), but if i do 'if count==n_line: ', the file ends up with a lot of garbage.
The Answers work, but i would like to know what are the problems with my code, and why i can't read and write. Thanks!
You are reading from the file and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Or if the size of the file is guaranteed to be small, you can use readlines() to read all of it, then close the file, modify the line you want, and write it back out:
def editline(file,n_line,text):
with open(file) as infile:
lines = infile.readlines()
lines[n_line] = text+' \n'
with open(file, 'w') as outfile:
outfile.writelines(lines)
Use temporary file:
import os
import shutil
def writeline(filename, n_line, text):
tmp_filename = filename + ".tmp"
count = 0
with open(tmp_filename, 'wt') as tmp:
with open(filename, 'rt') as src:
for line in src:
count += 1
if count == n_line:
line = line.replace(str(line), text + '\n')
tmp.write(line)
shutil.copy(tmp_filename, filename)
os.remove(tmp_filename)
def create_test(fname):
with open(fname,'w') as f:
f.write('1 \n2 \n3 \n4 \n5')
if __name__ == "__main__":
create_test('writetest.txt')
writeline('writetest.txt', 4, 'This is the fourth line')

Error: Getting symbols in python output

#I wrote the following code for making a text editor.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()
After the promp to write something in the file, the script goes awry and produces strange symbols instead of the typed text. Please help
You need to close and re-open your file.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
t.close() ##########
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
f.close() ##########
f = open(name, 'r+') ##########
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()

How to read and divide individual lines of a file in python?

Thanks to stackoverflow, I am able to read and copy a file. However, I need to read a picture file one line at a time, and the buffer array can't exceed 3,000 integers. How would I separate the lines, read them, and then copy them? Is that the best way to execute this?
Here is my code, courtesy of #Chayim:
import os
import sys
import shutil
import readline
source = raw_input("Enter source file path: ")
dest = raw_input("Enter destination path: ")
file1 = open(source,'r')
if not os.path.isfile(source):
print "Source file %s does not exist." % source
sys.exit(3)
file_line = infile.readline()
try:
shutil.copy(source, dest)
infile = open(source,'r')
outfile = open(dest,'r')
file_contents = infile.read()
file_contents2 = outfile.read()
print(file_contents)
print(file_contents2)
infile.close()
outfile.close()
except IOError, e:
print "Could not copy file %s to destination %s" % (source, dest)
print e
sys.exit(3)
I added
file_line = infile.readline()
but I'm concerned that infile.readline() will return a string, instead of integers. Also, how do I limit the number of integers it processes?
I think you want to do something like this:
infile = open(source,'r')
file_contents_lines = infile.readlines()
for line in file_contents_lines:
print line
This will get you all the lines in the file and put them into a list containing each line as an element in the list.
Take a look at the documentation here.

Python extracting first matching instance from multiple files

I have written a code which opens multiple files in a directory and prints only the first instance of match of required text from each file as output.
Now I want this output in a file. Doing it simply by putting print >> file.txt,... or .write or csv.write inside loop will not serve the purpose.
My code is:
import re, os, csv, sys
path = "D:\\"
in_files = os.listdir(path)
moldesc = ['Match1', 'Match2']
for f in in_files:
file = os.path.join(path, f)
text = open(file, "r")
for line in text:
if moldesc[0] in line:
Text1 = line.split()[-1]
if moldesc[1] in line:
Text2 = line.split()[-1]
print f, Text1, Text2 # I WANT THIS OUTPUT IN A FILE
break
text.close()
print "We are extraction done !!!"
you managed to open a file for reading, that's just one step away from opening a file for writing.
out = open(outfile, "w")
for f in in_files:
...
output_string = "{},{},{}\n".format(f, HOMO, LUMO)
out.write(output_string)

Categories

Resources