How can I convert this matlab code to python? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a Matlab code implementing a for loop which I have to convert it to python code:
for i = 1:numel(file_list)
filename = file_list(i).name;
File_list consists of 207 CSV files having 3036*190 items. this is how the following part of the code looks like:
for i = 1:numel(file_list)
filename = file_list(i).name;
SS= strcat(filename);
ActualRadarData = csvread(SS);
RadarData = real(ActualRadarData(:,20:end));
and this is what I attempted in doing so which is not correct:
for i in 1:len(file_list):
filename = os.path.basename('/path/file_list')
This method doesn't work out. how can it be done correctly?

Python starts indexes at zero, unlike MATLAB which starts indexing at 1, so you should keep that in mind. If you want to iterate through a list, you'd usually do for element in list, although you could iterate through indexes as well.
import os
for file in file_list:
filename = os.path.basename(file)
I would recommend looking into a guide for indexing and looping in Python, and then for CSV reading I recommend using Pandas.

Related

I cannot assign a variable with Python's falsy [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm stuck. I want to assign a variable asset to a CSV file, if the file is absent, a second file is sought.
I got this code but it seems not to work.
a = pd.read_csv('me.csv') or 'report_generator.csv'
print(a)
You could try something like this:
import pandas as pd
try:
df = pd.read_csv('one.csv')
except:
df = pd.read_csv('two.csv')
print(df.head())
It would try to open 'one.csv', and if any error occurs (note that the error could be even if the csv exists but the data was corrupted), then it would open 'two.csv'.
[EDITED]
A more beautiful and safe solution would be checking whether the file exists explicitly:
import os.path as path
if path.exists('one.csv'):
df = pd.read_csv('one.csv')
elif path.exists('two.csv'):
df = pd.read_csv('two.csv')
else:
print("Could not find csv")

Is there a way to get all keys that match a string in a json file's values and output them to a text file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to get all keys' values that equal "url" ignoring nesting from a JSON file and then output them to a text file. How would I go about doing this?
I'm running Python 3.7 and cannot seem to find a solution.
r = requests.get('https://launchermeta.mojang.com/mc/game/version_manifest.json')
j = r.json()
The result expected from this would be a text file filled with links from this json file.
https://launchermeta.mojang.com/v1/packages/31fa028661857f2e3d3732d07a6d36ec21d6dbdc/a1.2.3_02.json
https://launchermeta.mojang.com/v1/packages/2dbccc4579a4481dc8d72a962d396de044648522/a1.2.3_01.json
https://launchermeta.mojang.com/v1/packages/48f077bf27e0a01a0bb2051e0ac17a96693cb730/a1.2.3.json
etc.
Using requests library
import requests
response = requests.get('https://launchermeta.mojang.com/mc/game/version_manifest.json').json()
url_list = []
for result in response['versions']:
url_list.append(result['url'])
print(url_list)

Extract data from JSONs inside the CSV [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Could you advise what would be the best way to extract an element from JSON when I have multiple JSONs in a CSV file?
The data structure is like this
Line1: {"CreationTime":"2018-10-29T13:40:13","Id":"35127aae-a888-4665-6514-08d63da40e14","Operation":....,"IPaddress":"x.x.x.x"...}
Line 2: {"CreationTime":"2018-10-29T13:41:13","Id":"35127aae-a888-4665-6514-08d63da40e14","Operation":....,"IPAddress":"x.x.x.x"...}
.....
LineYY:...
My goal is to extract the IPAddress value from every line, that means from every json array. What would be the best way to do it?
Thanks a lot!
You can use json to load each line into a dictionary and then access IPAddress
import json
ips = []
for line in data.readlines():
row = json.loads(line)
ips.append(row['IPAddress'])

Formatting Numbers Inside of a String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Currently I'm working with an API of an online game I play to build a tool, and in doing so I've encountered a problem. The API returns JSON files to the user. While working on creating a class that parses these JSON files for me I've realized I'd like to be able to format a number inside of one of them so instead of being "585677088.5" it's "585,677,088". This would be easy enough if the string just contained this number however this string contains a bunch of other text as well.
Here's a block of the text
loan:0
unpaidfees:-3510000
total:585677088.5
I'm using python to do this.
The only existing code I have in place is:
import urllib2
data = urllib2.urlopen("URL")
Like this:
>>> my_str = """loan:0
... unpaidfees:-3510000
... total:585677088.5"""
>>> map(lambda x: (x.split(":")[0], int(float(x.split(":")[-1]))), my_str.split("\n"))
[('loan', 0), ('unpaidfees', -3510000), ('total', 585677088)]

How do I read a text file into a string variable in Python starting at the second line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use the following code segment to read a file in python
file = open("test.txt", "rb")
data=file.readlines()[1:]
file.close
print data
However, I need to read the entire file (apart from the first line) as a string into the variable data.
As it is, when my files contents are test test test, my variable contains the list ['testtesttest'].
How do I read the file into a string?
I am using python 2.7 on Windows 7.
The solution is pretty simple. You just need to use a with ... as construct like this, read from lines 2 onward, and then join the returned list into a string. In this particular instance, I'm using "" as a join delimiter, but you can use whatever you like.
with open("/path/to/myfile.txt", "rb") as myfile:
data_to_read = "".join(myfile.readlines()[1:])
...
The advantage of using a with ... as construct is that the file is explicitly closed, and you don't need to call myfile.close().

Categories

Resources