How can i modify information in a .properties file through python - python

i have a .properties file that statesserver-ip= and i made a python program that identifies my ipv4, but i want it to go to the proprieties file through the same program and get server-ip=(my ipv4)
import socket
socket.gethostbyname(hostname)
I've tired many diferent types of solutions, please a need help

If .properties doesn't have sections (usually doesn't) you could check this answer: - link
Else, you could use configParser:
import configparser
config = configparser.ConfigParser()
config.read('filename')
host = config['section-name']['server-ip']

Related

Opening a file on the desktop regardless of username

I'm trying to open a file on my laptop with Python and to do that I have the following code:
filem = open("C:\\Users\\david\\Desktop\\project\\last_msg_m.txt")
This works fine but I'm trying to adapt it so that it works independent of username so I used the following:
filem = open("C:\\Users\\"+ l1 +"\\Desktop\\project\\last_msg_m.txt")
However it doesn't work so I was wondering if there is another way to do it?
Simply use %userprofile%\desktop or %USERPROFILE%\Desktop as mentioned in the comments.
Otherwise you can also make use of the os module:
import os
username = os.getlogin() # Fetch username
file = open(f'C:\\Users\\{username}\\Desktop\\project\\last_msg_m.txt') # Use username var in f string
Windows only (to my knowledge):
So I tried using %userprofile% but it didn't seem to work for me so here is a different way to get it:
import os
user_profile = os.environ.get('USERPROFILE')
with open(fr'{user_profile}\Desktop\path\to\file') as file:
# do things with file
Using environment variables (also I suggest using context managers to open files)

How do i read from the command line with Python?

This code writes google.de has address 216.239.34.117 to the shell
import os
os.system("host google.de")
Now i want to save the IP-Address into a string variable, but i can`t figure out how i read from the command line. Or is there even an easier way to get the IP-Adress to a variable?
Thanks and Greetings,
Alex
Why won't you use socket library instead of os?
import socket
host_ip = socket.gethostbyname('google.de')
print(host_ip)

Open URL or local file in Python 3

I have a string.
I want:
If this string is an URL, I want to open this URL.
Otherwise, I want to open a local file with this name.
If there is no such object, raise an exception.
What is the correct and easy enough (if possible) way to do it in Python 3?
The main issue is the correct way to determine if a string is an URL.
Depends on what you mean by URL. If it's a web address, it will most usually start with http:// or https:// (usually, those are the cases you care about, anyway). However, it is possible that is also starts with ftp:// or some other protocol. However, most libraries accept URIs, which includes file URI. In that scheme, a file location looks like a URL that starts with file://, so you could pass your string, not caring whether it's a web address or a file, and the library will take care of it. There is no straight way of knowing whether the address is valid, but the library will throw an exception if it's not.
Try this:
import os
import webbrowser
import requests
webbrowser.open(s) if os.path.isfile(s) or requests.get(s) else exec("raise Exception")
This hasn't been tested, so treat it as psuedocode.
if s.startswith('http'):
# Do something
elif os.path.isfile(s):
file = open(s, 'r')
else:
raise Exception

Python - Download file over HTTP and detect filetype automatically

I want download a file via HTTP, but all the examples online involve fetching the data and then putting it in a local file. The problem with this is that you need to explicitly set the filetype of the local file.
I want to download a file but I won't know the filetype of what I'm downloading.
This is what I currently have:
urllib.urlretrieve(fetch_url,output.csv)
But if I download, say a XML file it will be CSV. Is there anyway to get python to detect the file that I get sent from a URL like: http://asassaassa.com/assaas?abc=123
Say the above URL gives me an XML I want python to detect that.
You can use python-magic to detect file type. It can be installed via "pip install python-magic".
I assume you are using python 2.7 since you are calling urlretreieve. The example is geared to 2.7, but it is easily adapted.
This is a working example:
import mimetypes # Detects mimetype
import magic # Uses magic numbers to detect file type, and does so much better than the built in mimetypes
import urllib # Your library
import os # for renaming your file
mime = magic.Magic(mime=True)
output = "output" # Your file name without extension
urllib.urlretrieve("https://docs.python.org/3.0/library/mimetypes.html", output) # This is just an example url
mimes = mime.from_file(output) # Get mime type
ext = mimetypes.guess_all_extensions(mimes)[0] # Guess extension
os.rename(output, output+ext) # Rename file

How can I open a Text file and find a specific strings value?

I'm using Python 3.4 on a Win32 platform. I want to open a file named somesettings.ini (just a text file) and search it until I find the value for a specific line. Specifically, I only want to pull out the current setting for the Minimum Free Space= line (see contents of the somesettings.ini below) and save it in a string for use elsewhere in the code. In the example of the ini file shown below, the string I want to end up with would be 32000.
Thanks in advance!
[Settings]
Idle Restart Time=300000
Minimum Free Space=32000
Max Record Time=1800
Deactive VR Timer=1800000
Use ERS=1
szaStorageDirectory=D:\
szaExportDirectory=Removable
szaConfigFile=C:\StreamsDefault.sdc
Enable LED=1
LED Port Address=3814
LED On Value=12
LED Off Value=4
LED Time Off=5900
LED Time On=100
Topmost Window=1
Grace Period=10000
Use Fast File Switching=1
You want to use configparser for this.
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read(r'somesettings.ini')
>>> config['Settings']['Minimum Free Space']
32000
You can access any of your settings in the [Settings] section this way.
At this point 32000 is a string. You will need to convert it to an int, if you expect an int later in the application:
>>> int(config['Settings']['Minimum Free Space'])
This code is for python 2.7:
f=open("somesettings.ini", "r")
for l in f.readlines():
If "Minimum Free Space" in l:
index=l.find('=')
res=l[index+1:]
break
f.close()

Categories