Python reading a text file but prints nothing - python

I tried different methods of printing out the text file. But it doesn't print anything.
There is code in the text file for sure, and I am spelling it right.
Why doesn't it print anything from the text file?
f = open("quotes.txt", "r")
print("Name of the file:", f.name)
line = f.readline()
print("Read Line: %s" % line)
data = f.read()
print("Data: ", data)
f.close()
This is what it prints:
Name of the file: quotes.txt
Read Line:
Data:

Related

How to get some characters after a specific string and use it as file name

I have a multiline string, which needs to be pasted and saved into a .txt file. I need also use some characters from the string as file name.
Here is an input example:
ABCD 0000/20/02
Q) abc/yxz/IV/A /000/999
A) XYZ B) 2008311600 C) 2009301559
E) texttexttext
texttext
File name should contain 6 numbers after B) : 200831 and the extension txt.
That's what I have:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
file_name= line[line.find("B) ")[6]:]
print (file_name)
with open(input(file_name + '.txt', "w+")) as f:
for line in lines:
f.write(line)
f.write('\n')
You could use regex to find out file name:
import re
string = '''ABCD 0000/20/02<br />
Q) abc/yxz/IV/A /000/999<br />
A) XYZ B) 2008311600 C) 2009301559<br />
E) texttexttext<br />
texttext<br />'''
filename = re.findall('B\) (\d\d\d\d\d\d\d)', string)[0]
with open(f'{filename}.txt', 'w') as f:
f.write(string)
Output file is 2008311.txt
so here i'm pasting my input, which is multiline string:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
Now i need to simply use those 6 characters from already pasted input in file name
In your code, all lines need to be checked, not only one line, so:
for line in lines:
if "B)" in line:
file_name = line[line.find("B) ")[6]:]
print (file_name)
Then, it is not really clear from your question whether you keep all multiline strings in memory or in separate files. Either way, you can write a function so that you can use it in different scenarios:
def parse_lines(lines):
for line in lines:
if "B)" in line:
file_name = line[line.find("B) ")[6]:]
print (file_name)
with open(file_name + '.txt', "w+") as f:
for line in lines:
f.write(line)
f.write('\n')
So your code will look like this:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
parse_lines(lines):
Or if you plan to parse batch files with this method:
import sys
with open(sys.argv[0], 'r') as f:
lines = f.readlines()
parse_lines(lines)

How to read a file and print it, skipping certain lines in python

I would like to read a file line by line but ignore any that contain a colon (:).
I'm currently opening one file, reading it, and trying to print it before eventually put it into a new file.
def shoppinglist():
infile = open('filename.txt')
contents = infile.readline()
output = open('outputfilename.txt', 'w')
while ":" not in contents:
contents = infile.readline()
else:
contentstr = contents.split()
print(contentstr)
output.write(contents)
infile.close()
output.close()
As it is, one line is repeated over and over and over.
Try:
def shoppinglist():
contents = ""
with open('filename.txt', 'r') as infile:
for line in infile.readlines():
if ":" not in line:
contents += line
with open('outputfilename.txt', 'w') as output_file:
output_file.write(contents)

Python, check if multiple files are empty-print results to separate file

I have list of files for which i need to check if they're empty or not
if they are non-empty print file name and file content, else do nothing
for example: file 1.html content: a, 2.html content: b, 3.html -empty
need to create resulting file with content of both files:
output.txt:
1.html
a
2.html
b
i have this code:
import os
files = ["1.html", "2.html", "3.html"];
for i in range(len(files)):
with open(files) as file:
first = file.read(1)
if not first:
print('') #nothing to print
else:
print file #print file name
print file.read() #print file content
and getting:
with open(files) as file:
TypeError: coercing to Unicode: need string or buffer, list found
You're complicating it too much, just load the file contents upfront - print it if there's something, ignore if not:
files = ["1.html", "2.html", "3.html"]
for filename in files:
with open(filename, "r") as f:
contents = f.read()
if contents:
print(filename)
print(contents)
for file in files:
with open(file) as fin:
if fin.read():
print file
print file.read()
You render your with statement moot since you are opening the initial array, and not files[i]. The better way to handle this is:
files = ["1.html", "2.html", "3.html"];
for f in files:
with open(f) as file:
first = file.read(1)
if not first:
print('') #nothing to print
else:
print f #print file name
print file.read() #print file content

Python continuous writing failed [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 6 years ago.
I want to read and write files multiple times.But the way is failed,it only writes the last modified content rather than all modified contents.
The incorrect program
def openfile():
txt = open("test.txt", "r")
contents = txt.readlines()
txt.close()
return contents
def write_file(contents,f):
old_contents = openfile()
old_contents.insert(1,contents)
contents = "".join(old_contents )
f.write(contents)
f.close()
text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)
text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)**
Worry Output
test2
My hope output
test1
test2
This is too much of code for the File Open and Write, You can just use this following lines to append the text in your file
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
Here, when we using this line open(filename, "a"), the a indicates the appending the file, that means allow to insert extra data to the existing file
as stated in the python doc you need to open your file with mode='a' if you want to append to existing data; mode='w' simply overwrites:
with open(file='_test.txt', mode='a') as file:
file.write('test')
(if you are using python 2, change the variable name file above to something else; in python 2 file is a keyword).
The reason for your "Worry Output" is that you re-open "test.txt" in read mode inside openfile after you've already opened it in write mode outside the functions. When you open a file in write mode it gets truncated, i.e., the file pointer is positioned to the start of the file and the current contents of the file are discarded. So when you call openfile inside write_file the file is empty, and thus openfile returns an empty list.
Here's a repaired version of your code. We use try... except in openfile so we can return an empty list if the file doesn't exist.
def openfile(fname):
try:
f = open(fname, "r")
contents = f.readlines()
f.close()
return contents
except FileNotFoundError:
return []
def write_file(contents, fname):
old_contents = openfile(fname)
old_contents.insert(1,contents)
contents = "".join(old_contents)
f = open(fname, "w")
f.write(contents)
f.close()
contents= "test1 \n"
write_file(contents, "test.txt")
contents = "test2 \n"
write_file(contents, "test.txt")
And here are the contents of "test.txt" after running that code:
test1
test2
Actually, it's better to use with when opening files:
def openfile(fname):
try:
with open(fname, "r") as f:
contents = f.readlines()
return contents
except FileNotFoundError:
return []
def write_file(contents, fname):
old_contents = openfile(fname)
old_contents.insert(1,contents)
contents = "".join(old_contents)
with open(fname, "w") as f:
f.write(contents)
However, a much better way to do this is to simply open the file in append mode as hiro protagonist and K.Suthagar have already shown. But I figured it was a good idea to explain why your current code didn't do what you expected it to do.
text1 = open("test.txt","w")
It is because above code resets the content. "w" is to override the file content.
Below code should explain you where you went wrong-
def openfile():
txt = open("test.txt", "r")
contents = txt.readlines()
print "Openfile method- Contents: "+str(contents)
txt.close()
return contents
def write_file(contents,f):
print "WriteFile method- Content received: "+str(contents)
old_contents = openfile()
print "Writefile method- Old content read from file: "+str(old_contents)
old_contents.insert(1,contents)
print "Writefile method- Old content after insertion: "+str(old_contents)
contents = "".join(old_contents )
print "WriteFile method- Content to write: "+str(contents)
f.write(contents)
f.close()
text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)
text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)
As mentioned, use "a" to append to file.

Search, count and add - Python

properties = ["color", "font-size", "font-family", "width", "height"]
inPath = "style.css"
outPath = "output.txt"
#Open a file for reading
file = open(inPath, 'rU')
if file:
# read from the file
filecontents = file.read()
file.close()
else:
print "Error Opening File."
#Open a file for writing
file = open(outPath, 'wb')
if file:
for i in properties:
search = i
index = filecontents.find(search)
file.write(str(index), "\n")
file.close()
else:
print "Error Opening File."
seems to work, but:
It only searches a keyword once?
Its not writing to the output file. function takes exactly 1 argument
I don't want it to print the index actually, but the number of time the keyword appears.
Many thanks
First, you want .count(search), not .find(search), if what you're looking for is # of occurrences.
Second, .write() only takes a single parameter - if you want to write a newline, you need to concatenate it first, or call .write() twice.
Third, doing for i in properties: search = i is redundant; just use the name you want in your for loop.
for search in properties:
cnt = filecontents.count(search)
file.write(str(cnt) + "\n")
from itertools import imap
properties = ("color", "font-size", "font-family", "width", "height")
inPath = "style.css"
outPath = "output.txt"
try:
#Open a file for reading
filecontents = file(inPath).read()
except Exception as exc:
print exc
else:
#Open a file for writing
with open(outPath, 'wb') as out_file:
#for property in properties:
# out_string = "%s %s\n"
# out_file.write( out_string % (
# property, filecontents.count(property)))
outfile.write('\n'.join(
imap(str, imap(filecontents.count, properties))))

Categories