git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Hi how do I import files inside a txt file?


On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
> Spencer Du <spencerdu at 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