How to open a file of different extension with notepad in python - python

I have a .fhx file that I could open normally with notepad but I want to open it using Python. I have tried subprocess.popen which I got online but I keep getting errors. I also want to be able to read the contents of this file like a normal text file like how we do in f=open("blah.txt", "r") and f.read(). Could anyone guide me in the right direction ?
import subprocess
filepath = "C:\Users\Ch\Desktop\FHX\fddd.fhx"
notePath = r'C:\Windows\System32\notepad.exe'
subprocess.Popen("%s %s" % (notePath, filepath))

Solved my problem by adding encoding="utf16" to the file open command.
count = 1
filename = r'C:\Users\Ch\Desktop\FHX\27-ESDC_CM02-2.fhx'
f = open(filename, "r", encoding="utf16") #Does not work without encoding
lines = f.read().splitlines()
for line in lines:
if "WIRE SOURCE" in line:
liner = line.split()
if any('SOURCE="INPUT' in s for s in liner):
print(str(count)+") ", "SERIAL INPUT = ", liner[2].replace("DESTINATION=", ""))
count += 1
Now I'm able to get the data the way I wanted.Thanks everyone.

try with shell=True argument
subprocess.call((notePath, filepath), shell=True )

You should be passing a list of args:
import subprocess
filepath = r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
notePath = r'C:\Windows\System32\notepad.exe'
subprocess.check_call([notePath, filepath])
If you want to read the contents then just open the file using open:
with open(r"C:\Users\Ch\Desktop\FHX\fddd.fhx") as f:
for line in f:
print(line)
You need to use raw string for the path also to escape the f n your file path name, if you don't you are going to get errors.
In [1]: "C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[1]: 'C:\\Users\\Ch\\Desktop\\FHX\x0cddd.fhx'
In [2]: r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[2]: 'C:\\Users\\Ch\\Desktop\\FHX\\fddd.fhx'

Related

How to open and print the contents of a file line by line using subprocess?

I am trying to write a python script which SSHes into a specific address and dumps a text file. I am currently having some issues. Right now, I am doing this:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it. However, this really messes up the format when I print "need". Is there any way to simply use subprocess and read the file line by line? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated :)
You don't need to use the subprocess module to print the entire file line by line. You can use pure python.
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)

Python: Unable to open and read a file

I am totally new to python.
I was trying to read a file which I already created but getting the below error
File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile
My code:
filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()
Also I tried
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
But same errors I am getting.
Try:
fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
print 'File does not exist'
return
with open(fpath, 'r') as src:
src.read()
First you validate that file, that it exists.
Then you open it. With wrapper is more usefull, it closes your file, after you finish reading. So you will not stuck with many open descriptors.
I think you're probably having this issue because you didn't include the full filename.
You should try:
filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()
*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call:
filename = open(newfile.txt
I had the same problem. Here's how I got it right.
your code:
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
Try this:
with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())
Hope it helps.
I am using VS code. If I am not using dent it would not work for the print line. So try to have the format right then you will see the magic.
with open("mytest.txt") as myfile:
print(myfile.read())
or without format like this:
hellofile=open('mytest.txt', 'r')
print(hellofile.read())

Error when trying to read and write multiple files

I modified the code based on the comments from experts in this thread. Now the script reads and writes all the individual files. The script reiterates, highlight and write the output. The current issue is, after highlighting the last instance of the search item, the script removes all the remaining contents after the last search instance in the output of each file.
Here is the modified code:
import os
import sys
import re
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f
infile = open(filepath, 'r+')
source_content = infile.read()
color = ('red')
regex = re.compile(r"(\b be \b)|(\b by \b)|(\b user \b)|(\bmay\b)|(\bmight\b)|(\bwill\b)|(\b's\b)|(\bdon't\b)|(\bdoesn't\b)|(\bwon't\b)|(\bsupport\b)|(\bcan't\b)|(\bkill\b)|(\betc\b)|(\b NA \b)|(\bfollow\b)|(\bhang\b)|(\bbelow\b)", re.I)
i = 0; output = ""
for m in regex.finditer(source_content):
output += "".join([source_content[i:m.start()],
"<strong><span style='color:%s'>" % color[0:],
source_content[m.start():m.end()],
"</span></strong>"])
i = m.end()
outfile = open(filepath, 'w+')
outfile.seek(0)
outfile.write(output)
print "\nProcess Completed!\n"
infile.close()
outfile.close()
raw_input()
The error message tells you what the error is:
No such file or directory: 'sample1.html'
Make sure the file exists. Or do a try statement to give it a default behavior.
The reason why you get that error is because the python script doesn't have any knowledge about where the files are located that you want to open.
You have to provide the file path to open it as I have done below. I have simply concatenated the source file path+'\\'+filename and saved the result in a variable named as filepath. Now simply use this variable to open a file in open().
import os
import sys
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f # This is the file path
infile = open(filepath, 'r')
Also there are couple of other problems with your code, if you want to open the file for both reading and writing then you have to use r+ mode. More over in case of Windows if you open a file using r+ mode then you may have to use file.seek() before file.write() to avoid an other issue. You can read the reason for using the file.seek() here.

os.path.join does not yield the contents of the file

print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink? "
category = raw_input()
for x in os.listdir(category): print x
name = raw_input("Which recipe would wou like to view? ")
fullname = os.path.join(category, name)
f = open(fullname, "r");
print f
I am writing a program that will allow users to view the contents of .txt files saved in specific directories. When I run this code I don't get the contents and instead get a message that says this:
open file 'savory/b.txt', mode 'r' at 0x1004bd140
any ideas. I am new to python so i dont have much of an idea as to what is causing the error but i assume it is due to some missing code.
Thank you.
The return value of open is a file object (not the file contents!) .You need to call a method on your file object to actually read the file:
f = open(fullname, "r")
print f.read()
f.close()
If it's a big file you may want to iterate over the file line-by-line
f = open(fullname, "r")
for line in f:
print line
f.close()
On a side note, here's alternate syntax to you don't have to remember to call the close method:
with open(fullname, "r") as f:
for line in f:
print line

Confusing Error when Reading from a File in Python

I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.

Categories

Resources