Combine variable with variable and text in Python [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I wondering what i am doing wrong here..
The issue is this line *final = 'PAT_' SID '.txt'*
where SID is a variable
Can anybody have a quick look, I am sure I am doing something stupid.
Below is the complete code...
#!/usr/bin/env python
import os
global SID
global final
with open ('sampleID.txt', 'r') as inF:
for line in inF:
if 'Sample ID:' in line:
SID = line.split(':')[1]
final = 'PAT_' SID '.txt'
os.rename("sampleID.txt",final)

To concatenate variables, you need to add (+) them:
final = 'PAT_' + SID + '.txt'
You can also use the built-in function str.format() here:
final = 'PAT_ {} .txt'.format(SID)
Or even the old way of string formatting, which is still compatible in Python 3 (but str.format is much better to use):
final = 'PAT_ %s .txt' % SID
By the way, your global statements aren't needed. A with statement does not introduce a new scope, hence everything defined in a with statement is a global variable.

use + to concat strings in python

Related

Find name in textfile [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
im new to python (I started yesterday) and wanted to make a program, in which you can enter a name, and then searches for the name in a text file and displays if the name exists or not. If I run the program and enter a existing name, it still shows "no" and I have no idea why. Can anyone help me out?
Here's a small code snippet which performs this logic:
def find_name_in_file(name, filename):
with open(filename, "r") as fd:
for line in fd.readlines():
if name in line:
return True # or print "YES"
return False # or print "NO"
Two things you need to keep in mind:
This code does not take into account case sensitivity, if name equals "Mark" and in the file the name is "mark" you will not find it (this can easily be resolved by using the "lower" function).
The function returns true also in cases where the file contains the word "SHMark" or "MarkSH". If you can't rely on the file having the exact name you are looking for you can add additional logic to check the word is surrounded by whitespace. I'll leave it to you to find out how to do it.

Escape characters when joining strings [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Trying to read a .csv file content from folder. Example code:
Files_in_folder = os.listdir(r"\\folder1\folder2")
Filename_list = []
For filename in files_in_folder:
If "sometext" in filename:
Filename_list.append(filename)
Read_this_file = "\\folder1\folder2"+max(filename_list)
Data = pandas.read_csv(Read_this_file,sep=',')
Fetching the max filename works, but the Data variable fails:
FileNotFoundError: no such file or directory.
I am able to access the folder as we see in my first line of code, but when I combine two strings, putting the r in front doesn't work, any ideas?
You need to add \ to your path when concatenating:
read_this_file = '\\folder1\\folder2\\' + max(filename_list)
But a better way to avoid that problem is to use
os.path.join("\\folder1\\folder2", max(filename_list))
for a working code, use this:
files_in_folder = os.listdir("folder1/folder2/")
filename_list = []
for filename in files_in_folder:
if "sometext" in filename:
filename_list.append(filename)
read_this_file = "folder1/folder2/"+max(filename_list)
data = pd.read_csv(read_this_file,sep=',')
Explanation:
When you put r before a string, the character following a backslash is included in the string without change, and all backslashes are left in the string.
In your example, if you try to print "\folder1\folder2" Python will read the '\f' part as a special character (just as it would for \n for example).

read .conf file python ConfigParser [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to read config.conf file in Python using ConfigParser. The thing I'm trying to do is, club $dataDir variable with a fileName and can't get expected output as given below.
config.conf
[dir]
dataDir = /home/srujan/Documents/r2d2/data-cut/SLIM/postcut
[files]
current_materiel = ${{dataDir}} + /20201209-rtvm_api_current_materiel_not_filtered_OS.csv
Expected output:
/home/srujan/Documents/r2d2/data-cut/SLIM/postcut/20201209-rtvm_api_current_materiel_not_filtered_OS.csv
Debug results - I get as a text instead of dataDir path.
${{dataDir}} + /20201209-rtvm_api_current_materiel_not_filtered_OS.csv
You are looking for https://docs.python.org/3/library/configparser.html#interpolation-of-values.
The default interpolation only allows use of variables from the same section with %(varname) syntax. If you want variables to persist across multiple sections, you need to use the extended interpolation
parser = configparser.ConfigParser(..., interpolation=configparser.ExtendedInterpolation())
Extended interpolation uses ${section:option} to denote a value from a foreign section.

Python: Using a list to execute arguements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Sorry if this is basic question I'm new to python and i couldn't find the proper way to do this within the api docs.
I have a list that contains stack arguments in the fashion
[push,3][push,2][push,1][pop][add]... so on
I also have a StackMachine.py file that created a class Stack:with the member functions push pop add sub mul div mod
I imported it into my main.py file and i want to go through my list and execute the arguments using the functions i made in my StackMachine.py file.
My question is how to analyze the list and use my member functions from the Stack class.
my main.py looks like
from StackMachine import Stack
import sys
toks = []
f = open(sys.argv[1])
for line in f.readlines():
tokens = line.split()
toks.append(tokens)
f.close()
It may not work because one you forgot the colon after the if statement, if i == "push": and if i == "pop":. For the push, 1 and push, 2 part you would be checking a tuple which is a data structure that is similar to a list but is immutable. So to check what the number is or what the first argument is you would do if i[0] == "push" and i[1] == 1: but before this if statement you would have to check if that object is a tuple so you would do if type = tuple:

Check if many URLs exists from a txt file (Python) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i'm new in python and I'm wanting to do what I said above, but I don't have any ideas, so how can I?
From the code in your comment (you should put this in your question), it is with reading the lines from a file that you're struggling.
The idiomatic way of doing this is like so:
with open("hello.txt") as f:
for line in f:
print line,
[See File Objects in the official Python documentation].
Plugging this into your code (and removing the newline and any spaces from each line with str.strip()):
#!/usr/bin/env python
import mechanize
br = mechanize.Browser()
br.set_handle_redirect(False)
with open('urls.txt') as urls:
for url in urls:
stripped = url.strip()
print '[{}]: '.format(stripped),
try:
br.open_novisit(stripped)
print 'Funfando!'
except Exception, e:
print e
Note that URLs start with a scheme name (commonly called a protocol, such as http), followed by a colon, and two slashes hence:
[stackoverflow.com]: can't fetch relative reference: not viewing any document
But
[http://stackoverflow.com/]: Funfando!
Open the file. Iterate through the lines. Fetch the files and check for errors.

Categories

Resources