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

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

Related

How to read a line while reading a file in Python

Imagine that another filename in the same directory is inside the txt file we're currently in:
For example, let file A be the following:
B.txt
computer
science
How would it be possible to read the other lines and go into B.txt after we're done reading?
If you want to read first line separately, you can do it with readline(). Loop then proceeds to read the file from the second line to the end of file:
import os
def read_files_to_list(wordlist, file):
with open(file, "r") as f:
newfile = f.readline()
newfile = newfile.strip() # removes \n and whitespaces
if not os.path.exists(newfile):
wordlist.append(newfile)
newfile = None
for line in f:
line_clean = line.strip()
wordlist.append(line_clean)
return wordlist, newfile
next_file = "A.txt"
listofwords = []
while next_file is not None:
listofwords, next_file = read_files_to_list(listofwords, next_file)

How to write in a dat file in python

I have this content in a dat file I can access easily, it's not at the beggining of the file but in the middle. I insert only the part of the file that I need to modify.
{
....,
",>=,",
",>=,",
.......
}
Instead of a line with ",>=,", I wish I could insert a custom string like for example
"M,<=,5", from python code, as I would have to do this on many files/many times.
I can read the file through this script, but I don't understand how to find the line I want to change in the python code and how to overwrite in it the string of my interest.
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
with open(prefixed[i], 'r') as file:
lines = file.readlines()
print(lines)
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()
To modify only the first element:
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Add break to quit loop after first replacement
break
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()

Go through files in given directory with python, read each file line by line and remove first and last string in the line and save updated file

So I have some .txt files inside of directory. Each .txt file contains some paths like:
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c'
I need just some small function that will go through each line of each file inside of a dir and remove there ', so only clear path is left like:
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c
My code at the moment is:
for filename in files:
with open(filename, 'r') as file:
content = file.read().split('\n')
for line in content:
if line.startswith('')and line.endswith(''):
remove('')
Please assist!
SOLUTION:
I have managed to find a solution with a bit different approach:
for filename in files:
f = open(filename, 'rt')
filedata = f.read()
filedata = filedata.replace("'","")
f.close()
f = open(filename, 'wt')
f.write(filedata)
f.close()
Thanks!
python has a hirarchy to strings ', ", "" and so on so you can wrap a uptick into quotes for a split. Since we have the first element '' before the tick the second is your path
line.split("'")[1]
Edit: If i understood you correctly you want this
for filename in files:
paths = []
with open(filename, 'r') as file:
content = file.read().split('\n')
for line in content:
paths.append(line.split("'")[1])
file.close()
with open(filename, 'w') as file:
file.writelines(paths)
file.close()
Soo I just did bit different approach and managed to find a solution:
for filename in files:
f = open(filename, 'rt')
filedata = f.read()
filedata = filedata.replace("'","")
f.close()
f = open(filename, 'wt')
f.write(filedata)
f.close()
Thanks guys anyway!

Comparing .txt files in Python using askdirectory

I have the below code to run through a directory and select all of the files and compare them to an inserted wordlist file. However I get the following error TypeError: invalid file: ['C:/Users/Nathan/Desktop/chats\\(1,).out'] I cannot figure out how to change the os.path.join to correctly show the file location.
self.wordopp = askdirectory(title="Select chat log directory")
path = self.wordopp
files = os.listdir(path)
paths = []
wordlist = self.wordop
for file in files:
paths.append(os.path.join(path, file))
f = open(wordlist)
l = set(w.strip().lower() for w in f)
with open(paths) as f:
found = False
file = open("out.txt", "w")
for line in paths:
line = line.lower()
if any(w in line for w in l):
found = True
file.write(line)
print(line)
if not found:
print(line)
Consider this line of code:
with open(paths) as f:
Ask yourself, "what is paths"? It is a list of filenames, not a single file. That's pretty much what the error is telling you: that a list is an invalid file.
Considering that you are looping over a list of filenames, my guess is that your intention is to do:
with open(file) as f:
or maybe
with open(paths[-1]) as f:

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.

Categories