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.
Related
I have a question about the python read files(its format as txt ). I read a file and argv[1] is once read bytes number, and then put it sotre in a list, but when I write it on another file, it is not the same as the original files. how could i fix this?
readfile:
fh = open(file_name, "rb")
imfor = fh.read(mss)
file_content = []
file_content.append(imfor)
while (imfor):
file_content.append(imfor)
imfor = fh.read(mss)
fh.close()
write File
fh = open("test1R.txt", "wb")
for currContent in file_content:
fh.write(currContent)
fh.close
It is always better to use a the with open context manager to read and write files. You also don't need to manually append the contents to a list. file.readlines() does that for you.
Here is a some code to help you with that:
from sys import argv
# we first check if the file exists
try:
print("reading file")
with open(argv[1], "r") as input_file:
file_contents = input_file.readlines() # stores the file content in an array
except FileNotFoundError:
print(f"File {argv[1]} not found")
exit(1)
# check if the user provided a name for the output file
try:
out_file = argv[2]
except IndexError:
out_file = "outfile.txt"
# write to the new file.
with open(out_file, "w") as out:
try:
out.write("\n".join(file_contents)) # converts the array back to string
print(f"Wrote to {out_file}")
except FileExistsError:
print(f"{out_file} already exists.")
exit(1)
This Python code runs but prints the last page of the text file. Not sure why, but I aim to print the whole line of text that is underneath a specified line of text (a line that contains the specific string ** Direct **). How can I loop through a text file, search each line for the specified string, and whenever it is found print the row directly below it? I have searched many online forums and have not found an easily understandable example. I use Python Sypder 2.7. Any help appreciated
import os
Path = '..\\Test.txt'
if os.path.isfile(Path):
with open(Path) as f:
for line in f:
print line
else:
print Path, "doesn't exist"
f.close()
Python 3.x:
dummy.txt
Mango
Anday Wala Burger
40
Aloo
Anday
Ghobi
Anday Wala Burger
30
Kheerey
Anday Wala Burger
py:
searchString = 'Anday Wala Burger'
with open('dummy.txt', "r") as input:
try:
for line in input:
if searchString in line:
print(next(input), end='')
except StopIteration:
pass
OUTPUT:
40
30
EDIT:
Python 2.7:
dummyFile= "dummy.txt"
searchString = 'Anday Wala Burger'
with open(dummyFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
# flag
nextLine = False
for line in content:
if searchString in line:
nextLine = not nextLine
else:
if nextLine:
print(line)
nextLine = not nextLine
else:
pass
OUTPUT:
40
30
You need to make some changes:
1.-Read the lines
2.- Compare with your text
import os
Path = '..\\Test.txt'
look='**Direct**'
if os.path.isfile(Path):
with open(Path, "r") as f:
for line in f:
if look in line:
print (line)
else:
print (Path, "doesn't exist")
Check out the re module. It includes the re.search() function, which searches for a pattern inside a string.
To print the next line you can take advantage of the fact that file objects are iterable, by using f.next().
For example, you could do:
import os
import re
Path = 'foo.txt'
Pattern = "spam" # String to be searched
if os.path.isfile(Path):
with open(Path) as f:
for line in f:
if re.search(Pattern, line):
print(f.next())
else:
print(Path, "doesn't exist")
By the way, you don't need that final f.close(). It is already taken care of by the with statement.
Check if one is in any line in the file and the print the next line as found will be the next lineno file will be set as currentlineno+1
Contents of file temp
one
two
three
four
Python file
with open('temp') as f:
found=-1
#no lines are found to print so found is negative in value since line no in a file cannot be negative
for index,line in enumerate(f):
if found==index:
print(line)
if 'one' in line:
found=index+1
# when the condition is True found is set to the line no that we need to print
Output
two
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
I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.
The error occurs at line 49 "fileSizeRemainingInBytes = os.path.getsize(inFile)"
inFile contains the file I want to gets size. From what I understood in the python documentation this should be correct. Can someone tell me what is the problem.
import sys, os
buffer = 1000
try:
#open file in binary mode for reading
inFile = open(sys.argv[1],"rb")
print "file name is: ", inFile.name
except IOError:
#check for IOExceptions
print "Eror opening file"
sys.exit()
else:
#create new directory for copying, create out file in new directory
if (os.path.isdir("recv")):
os.chdir("recv")
try:
outFile = open(inFile.name,"wb")
except IOError:
print "something went wrong creating the out file"
sys.exit()
else :
os.mkdir("recv")
os.chdir("recv")
try:
outFile = open(inFile.name,"wb")
except IOError:
print "something went wrong creating the out file"
sys.exit()
#loop to copy bytes to new directory
fileSizeRemainingInBytes = os.path.getsize(inFile)
print "Initial size: ", fileSizeRemainingInBytes
while fileSizeRemainingInBytes > 0 :
print fileSizeRemainingInBytes
bytesToCopy = inFile.read(buffer);
outFile.write(bytesToCopy);
inFile.close()
os.path.getsize takes a file path as an argument, not a file object. So you actually want to call os.path.getsize(inFile.name). Note that this won't give you the number of bytes remaining to copy; it'll just give you the size of the whole file every time it's evaluated. To get the number of bytes remaining, you'll have to keep track of the total number of bytes read and subtract this total from the file size.
Something like this should work:
import sys
import os
buffer = 1000
with open(sys.argv[1], "rb") as in_file:
# Make your `recv` directory as a sub-directory
# or your current directory if it doesn't already exist
if not os.path.isdir("recv"):
os.mkdir("recv")
# Create the path to the file to which you
# want to copy. When opened, you'll have a file
# with the same file name as your input file,
# but it will be in your `recv` subdirectory
out_file_path = os.path.join("recv", in_file.name)
# Read the bytes
with open(out_file_path, "wb") as out_file:
bytes_read = 0
bytes_to_read = os.path.getsize(in_file.name)
while bytes_read < bytes_to_read:
out_file.write(in_file.read(buffer))
bytes_read += min(buffer, bytes_to_read - bytes_read)
print "{} / {} bytes copied".format(bytes_read, bytes_to_read)