I had some problems with my Python code.
My code:
import os
logininfo = list()
with open(os.getcwd() + '/login/info.txt', 'r') as f:
logininfo = f.readlines()
But my code isn’t work, so how do I fix that?
Edit: I changed the quote and changed the ‘ to '
Problem 2: After I fix all that look like my computer is freeze now and I can’t even move my mouse. After freeze for a while, the code make my computer ran to BSOD. What happened?
Okay, I think I see what the problem in problem 2 that my file was too big with 50 GB of login information of my server. Thanks you guy for helping me solve the problem 1.
Your problem is likely that your / (forward slashes) are supposed to be \ (backslashes). It is also a good practice to use os.path.join() when concatenating file paths. Make sure login\info.txt does not have a backslash in front of it. I printed the list afterwards to make sure it was working. Windows file paths use \\.
import os
with open(os.path.join(os.getcwd(), 'login\info.txt'), 'r') as f:
logininfo = f.readlines()
print(logininfo)
Regardless of OS, I would recommend using pathlib module to deal with system paths and to decrease ambiguity in OS path handling.
So, regardless of OS, an API would be (including your code):
from pathlib import Path
file_path = Path.cwd() / 'login' / 'info.txt'
with open(file_path, 'r') as f:
login_info = f.readlines()
Get familiar with that module (it's out of the box!) here: https://docs.python.org/3/library/pathlib.html
I believe the wrong thing is that you're using double slashs, when it should be:
import os
with open(os.getcwd() + ‘/login/info.txt’, 'r') as f:
logininfo = f.readlines()
I reproduced the error here, created a file with the same folder structure as yours, and this definitely should work:
In [3]: with open(os.getcwd() + '/login/info.txt', 'r') as f:
...: lines = f.readlines()
...: for line in lines:
...: print(line)
...:
Olá,
deixa eu ver esse erro aqui
Related
I am a Python newbie and I am having a problem that probably has as a simple answer. I have the following script, which works most of the way, I just get stuck trying the write the output file. The error I get is at the very end: IOError: [Errno 2] No such file or directory: '/D/1_NEW_ANALYSIS/Scripts/Melodic_fsfs/design_Rat01_Run_1.fsf'
Here is the code:
import os
import glob
studydir = 'D:/1_NEW_ANALYSIS'
fsfdir="%s/Scripts/Melodic_fsfs"%(studydir)
templatedir="%s/Scripts/Templates"%(studydir)
subdirs=glob.glob("%s/Subjects/Rat_[0-9][0-9]/Run_[0-2]"%(studydir))
for dir in list(subdirs):
splitdir = dir.split('\\')
# YOU WILL NEED TO EDIT THIS TO GRAB sub001
splitdir_sub = splitdir[1]
subnum=splitdir_sub[-2:]
splitdir_run = splitdir[2]
runnum=splitdir_run[-1:]
print(subnum)
replacements = {'SUBNUM':subnum, 'RUNNUM':runnum}
with open("%s/Melodic_design.fsf"%(templatedir)) as infile:
with open("%s/design_Rat%s_Run_%s.fsf"%(fsfdir, subnum, runnum), 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)
Anybody have an idea why it doesn't work?
Thanks a lot!
If you are running on windows (I assume you are), studydir should look like:
studydir = 'D:\\1_NEW_ANALYSIS'
I have a bunch of .csh in a directory and I want to open them one by one, search for "//" and replace it with "/" with a python script. How do I do that?
I tried:
import os
for file in os.listdir("./"):
if file.endswith(".csh"):
with open(file, 'r+'):
data = file.read().replace("//", "/")
f.write(data)
f.close()
But it gives me:
File "script.py", line 4
with open(file, 'r+'):
^
SyntaxError: invalid syntax
You are using an old version of Python. The with statement was introduced in Python 2.5, where it had to be enabled via
from __future__ import with_statement
It is best to upgrade to 2.7, if you need to stay in the 2.x line, or 3.4.
Note that you also need to change your code according the answer by Avinash Raj, capturing the file object in a variable via as f. file.read() will not work because file continues to be the file name string.
Change your code to,
import os
for file in os.listdir("./"):
if file.endswith(".csh"):
with open(file, 'r+') as f:
data = f.read()
f.seek(0)
with open(file, 'w+') as w:
dat = data.replace("//", "/")
w.write(dat)
I'm trying to save a bunch of pages in a folder next to the py file that creates them. I'm on windows so when I try to make the trailing backslash for the file-path it makes a special character instead.
Here's what I'm talking about:
from bs4 import BeautifulSoup
import urllib2, urllib
import csv
import requests
from os.path import expanduser
print "yes"
with open('intjpages.csv', 'rb') as csvfile:
pagereader = csv.reader(open("intjpages.csv","rb"))
i=0
for row in pagereader:
print row
agentheader = {'User-Agent': 'Nerd'}
request = urllib2.Request(row[0],headers=agentheader)
url = urllib2.urlopen(request)
soup = BeautifulSoup(url)
for div in soup.findAll('div', {"class" : "side"}):
div.extract()
body = soup.find_all("div", { "class" : "md" })
name = "page" + str(i) + ".html"
path_to_file = "\cleanishdata\"
outfile = open(path_to_file + name, 'w')
#outfile = open(name,'w') #this works fine
body=str(body)
outfile.write(body)
outfile.close()
i+=1
I can save the files to the same folder that the .py file is in, but when I process the files using rapidminer it includes the program too. Also it would just be neater if I could save it in a directory.
I am surprised this hasn't already been answered on the entire internet.
EDIT: Thanks so much! I ended up using information from both of your answers. IDLE was making me use r'\string\' to concatenate the strings with the backslashes. I needed use the path_to_script technique of abamert to solve the problem of creating a new folder wherever the py file is. Thanks again! Here's the relevant coding changes:
name = "page" + str(i) + ".txt"
path_to_script_dir = os.path.dirname(os.path.abspath("links.py"))
newpath = path_to_script_dir + r'\\' + 'cleanishdata'
if not os.path.exists(newpath): os.makedirs(newpath)
outfile = open(path_to_script_dir + r'\\cleanishdata\\' + name, 'w')
body=str(body)
outfile.write(body)
outfile.close()
i+=1
Are you sure sure you're escaping your backslashes properly?
The \" in your string "\cleanishdata\" is actually an escaped quote character (").
You probably want
r"\cleanishdata\"
or
"\\cleanishdata\\"
You probably also want to check out the os.path library, particular os.path.join and os.path.dirname.
For example, if your file is in C:\Base\myfile.py and you want to save files to C:\Base\cleanishdata\output.txt, you'd want:
os.path.join(
os.path.dirname(os.path.abspath(sys.argv[0])), # C:\Base\
'cleanishdata',
'output.txt')
A better solution than hardcoding the path to the .py file is to just ask Python for it:
import sys
import os
path_to_script = sys.argv[0]
path_to_script_dir = os.path.dirname(os.path.abspath(path_to_script))
Also, it's generally better to use os.path methods instead of string manipulation:
outfile = open(os.path.join(path_to_script_dir, name), 'w')
Besides making your program continue to work as expected even if you move it to a different location or install it on another machine or give it to a friend, getting rid of the hardcoded paths and the string-based path concatenation means you don't have to worry about backslashes anywhere, and this problem never arises in the first place.
I modified the code based on the comments from experts in this thread. Now the script reads and writes all the individual files. The script reiterates, highlight and write the output. The current issue is, after highlighting the last instance of the search item, the script removes all the remaining contents after the last search instance in the output of each file.
Here is the modified code:
import os
import sys
import re
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f
infile = open(filepath, 'r+')
source_content = infile.read()
color = ('red')
regex = re.compile(r"(\b be \b)|(\b by \b)|(\b user \b)|(\bmay\b)|(\bmight\b)|(\bwill\b)|(\b's\b)|(\bdon't\b)|(\bdoesn't\b)|(\bwon't\b)|(\bsupport\b)|(\bcan't\b)|(\bkill\b)|(\betc\b)|(\b NA \b)|(\bfollow\b)|(\bhang\b)|(\bbelow\b)", re.I)
i = 0; output = ""
for m in regex.finditer(source_content):
output += "".join([source_content[i:m.start()],
"<strong><span style='color:%s'>" % color[0:],
source_content[m.start():m.end()],
"</span></strong>"])
i = m.end()
outfile = open(filepath, 'w+')
outfile.seek(0)
outfile.write(output)
print "\nProcess Completed!\n"
infile.close()
outfile.close()
raw_input()
The error message tells you what the error is:
No such file or directory: 'sample1.html'
Make sure the file exists. Or do a try statement to give it a default behavior.
The reason why you get that error is because the python script doesn't have any knowledge about where the files are located that you want to open.
You have to provide the file path to open it as I have done below. I have simply concatenated the source file path+'\\'+filename and saved the result in a variable named as filepath. Now simply use this variable to open a file in open().
import os
import sys
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f # This is the file path
infile = open(filepath, 'r')
Also there are couple of other problems with your code, if you want to open the file for both reading and writing then you have to use r+ mode. More over in case of Windows if you open a file using r+ mode then you may have to use file.seek() before file.write() to avoid an other issue. You can read the reason for using the file.seek() here.
I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.