On 3/09/19 1:48 AM, Spencer Du wrote:
On Monday, 2 September 2019 15:29:07 UTC+2, Joel Goldstick  wrote:
On Mon, Sep 2, 2019 at 9:21 AM Spencer Du <spence...@hotmail.co.uk> wrote:

On Monday, 2 September 2019 15:03:52 UTC+2, Joel Goldstick  wrote:
On Mon, Sep 2, 2019 at 8:46 AM Spencer Du <spence...@hotmail.co.uk> wrote:

On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
Spencer Du <spence...@hotmail.co.uk> writes:

How do i import files inside a txt file if they exist in the current directory?

Here is the current code but I dont know how to do it correctly.

import paho.mqtt.client as mqtt
from mqtt import *
import importlib
import os
import os.path
# from stateMachine import *

with open("list_of_devices.txt", "r") as reader:
     for item in reader:
             try:
                     os.getcwd()
                     print("hi")
             except:
                     print("error")

This is "list_of_devices.txt":
test1,test2

Each name refers to a python file.

My interpretation is that you want to read a file (list_of_devices.txt)
and this file contains names of other files and you want to read those
files as well and do something with them (read or print or whatever).

You can approach it like this: write a function to read a file and work
on it. Like this,

def fn(fname):
     with open(fname, "r") as f:
          try:
                 # work with f
          except:
                 print("error")

Then use this function in your code that you have writen. Like this

with open("list_of_devices.txt", "r") as reader:
      for item in reader:
          try:
                 fn(item)
          except:
                 print("error")

In the example that you gave, you have written contents of
"list_of_devices.txt" as

test1,test2

Take care to read them as comma separated. Or if you have control then
write them on separate lines.

Regards.
--
Pankaj Jangid

Hi Pankaj

I dont understand so what is complete code then?

Thanks
Spencer
--
https://mail.python.org/mailman/listinfo/python-list

Pardon me for guessing, but your question seems to imply that you know
how you want to do something .. but I'm not sure you have tackled your
problem correctly.

My guess is:  Depending upon the names listed in a text file, you want
to do different imports into your program.   You don't yet know how to
read a file with python.

First, when you run your program, python compiles it in order.  Since
you don't know what you want to import until after you run your
program, you can't import those modules.  You may be able to run a
program to read the module list, then have it output to a new file the
code you eventually want to run based on the modules you discovered.
That sounds cute in a way, but probably not in a good way.  You could
also surround import statements with try/except code that will import
what it can, and alert you when it can't

Can you give us the bigger picture of what you want to accomplish?
This might lead to a better solution than the one you are thinking of
now

--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

Hi

I have a txt file which contains the names of files. They are .py files. I want 
to import them into a python file if they exists in current directory and if 
the name of file does not exist then print out error and not import. How do I 
do this?

Thanks
Spencer

Here is a discussion on Stack overflow that lays out how you can
dynamically import files.  This should get you started in the right
direction.  First, see if you can write code to read the file, and
retrieve the names of the modules you want to import.   Come back if
you stumble with your code for that

https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string
--
https://mail.python.org/mailman/listinfo/python-list



--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

Ok I have this code to retrieve the names of modules I want to import. Now how 
do I check if they exist in current directory and if they exist import them 
into the python program. Thanks.

with open("list_of_devices.txt", "r") as f:
        for item in f:
                print(item)


Perhaps it is time to slow-down and take a breather?

The answer to this step has already been covered in this thread!


Many languages require one to *anticipate* every contingency - anything that could go 'wrong'. For example, that a file does not exist and cannot be imported.

However, Python follows a philosophy that it is "easier to ask forgiveness than it is to get permission"*. In other words, to use the try...except construct - in this case, to attempt an import (the "try") and if that fails (probably because the file does not exist) then to defend/react accordingly (the "except" - "except" = "exception").

In other words, only worry about 'the problem' (post fact), should it arise. This works quite neatly for your use-case.


Such is what is called "a Python idiom" - the way things are done in Python (which may be fundamentally different from other programming language(s) you use). It is a mistake to attempt to 'translate' from one programming language into another merely by replacing one "syntax" with the other. For example a Python for-loop is actually a 'foreach' construct and thus not the same as the C/C++, FORTRAN, BASIC, etc, etc, for-loop - no matter what the words say! Learning (and absorbing) idioms and language philosophies is what separates better programmers from the mediocre!


Are you taking the time to research? Have you reviewed the Python docs*?


If you must check for the presence of a file, entering "python file exists" into a search engine produces numbers of 'hits'!

The hard way (the syntax-only 'translation', and non-Pythonic approach), is that the PSL offers "11.2. os.path — Common pathname manipulations"*


* WebRefs:
https://en.wikiquote.org/wiki/Grace_Hopper
https://docs.python.org/3.6/index.html [adjust versionNR to suit]
https://stackabuse.com/python-check-if-a-file-or-directory-exists/

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to